I have a nested list like below:
Zeros = [[1], [2], [3, 4], [5, 6]]
How can I separate each element and make a list of tuples, like below:
Modified_zeros = [(1), (2), (3), (4), (5), (6)]
Thanks
You can try iterating each element in the nested list and finally adding the single element in brackets with ,
. There are other similar answers to create tuples.
results = [(j,) for i in Zeros for j in i]
Output:
[(1,), (2,), (3,), (4,), (5,), (6,)]
Based off this answer:
flat_list = [(item,) for sublist in l for item in sublist]
Where l
is your original list (Zeros in your case)
for nested list at multiple level
Zeros = [[1], [2], [3, 4], [5, 6,[1,2,3,4]]]
def fun(l):
res=[]
if isinstance(l,list):
for i in l:
res.extend(fun(i))
elif isinstance(l,int):
res.append((l,))
return res
print(fun(Zeros))
output
[(1,), (2,), (3,), (4,), (5,), (6,), (1,), (2,), (3,), (4,)]