2

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

Hey There
  • 275
  • 3
  • 14

3 Answers3

2

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,)]
niraj
  • 17,498
  • 4
  • 33
  • 48
  • Hi, Thanks, How can I get rid of the comma after the numbers? – Hey There May 31 '19 at 22:48
  • 1
    If you do not have comma then, it is no longer tuples. https://stackoverflow.com/questions/12876177/how-to-create-a-tuple-with-only-one-element – niraj May 31 '19 at 22:48
1

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)

Jack Thomson
  • 450
  • 4
  • 9
0

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,)]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44