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

Fill in uneven sized lists in Python

I have a 2D-List contains unequal size numers, like this:

lst = [[1,2,3],[-1,2,4],[0,2],[2,-3,6]]

I use this code to insert a 0 if element size less 3:

newlist = [val.insert(1,0) for val in lst if len(val)<3]

But I just got an empty newlist and the original lst was inserted into a 0.

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

>>> lst = [[1,2,3],[-1,2,4],[0,2],[2,-3,6]]
>>> newlist = [val.insert(1,0) for val in lst if len(val)<3]
>>> newlist
[None]
>>> lst
[[1, 2, 3], [-1, 2, 4], [0, 0, 2], [2, -3, 6]]

I don’t want use old lst list value because if modified value can return to newlist, I can directly use it convert to a dataframe. like this:

df = pd.DataFrame([val.insert(1,0) for val in lst if len(val)<3])

So, how do I do this? And I hope the code can be written in a one-liner.

>Solution :

You are getting None as the value for newlist because val.insert(1,0) returns None as the output.

Try this instead,

lst = [[1,2,3],[-1,2,4],[0,2],[2,-3,6]]
new_list = [i + [0] if len(i) < 3 else i for i in lst]
print(new_list)

Output –

[[1, 2, 3], [-1, 2, 4], [0, 2, 0], [2, -3, 6]]
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