Skip to content
Advertisement

Extend the list with fixed values

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement