Home > Software engineering >  Extend the list with fixed values
Extend the list with fixed values

Time:02-15

I have the following list:

l = [5, 6, 7, 1]

I need to populate this list with the first value (i.e. 5) so that the length of this list becomes equal to 10.

Expected result:

l_extended = [5, 5, 5, 5, 5, 5, 5, 6, 7, 1]

I can do it in for loop:

fixed_val = l[0]
len_diff = 10 - len(l)
l_extended = []

for n in range(len_diff):
   l_extended.append(fixed_val)

for n in range(len_diff,10):
   l_extended.append(l[n-len_diff])

But is there any shorter way to do it?

CodePudding user response:

Also consider

a = [1,2,3]
a_extended = [ a[0] ] * ( 10-len(a) )   a

Explanation:

a[0] grabs the first element

(10-len(a)) is the number of characters we need to add to get the length to 10

In Python, you can do [1] * 3 to get [1,1,1], so:

[a[0]] * (10-len(a)) repeats the first element by how many extra elements we need

In python, you can do [1,2,3] [4,5,6] to get [1,2,3,4,5,6], so:

[a[0]]*(10-len(a)) a adds the extra elements onto the front of the list

CodePudding user response:

The shortest way is probably

l_extended = [*[l[0]]*(10 - len(l)), *l]

CodePudding user response:

I'd suggest:

lst_extended = [lst[0]] * (to_len - len(lst))   lst

[lst[0]] * some_number: an array containing some_number of the first element of your starting list.

to_len - len(lst): how long the first part of the new list needs to be. So if you want a list of 6 elements from a list of 4 elements, you need 2 extra elements.

some_list lst: join two lists together.

I prefer lst to l because it looks less like 1 and I.

  • Related