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.
>>> 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]]