Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading