3
votes

I'm trying to turn a nested list of lists (number of lists can be 2 lists +) into a single list of tuples.

The list looks something like this:

exampleList = [['A', 'B', 'C', 'D'], [1, 2, 3, 4], [10, 20, 30, 40]]

And I would like for it to be like this;

newList = [('A', 1, 10), ('B', 2, 20), ('C', 3, '30)...]

I know that if you do zip(list1, list2), it becomes a list of tuple. But how do I go about doing it for a list of lists?

I tried using the zip concept with:

test = []
for data in exampleList:
     test.append(zip(data))

But it did not work out for me.

Thanks in advanced for any help!

1
What's your actual expected output? Exactly newList but where the elements are lists rather than tuples? What's stopping you from doing something like newList = [list(e) for e in zip(*exampleList)]?Two-Bit Alchemist
Look at the manual for zip docs.python.org/3/library/functions.html#zip even the parameter list is shown as *iterablemsw

1 Answers

8
votes
>>> exampleList = [['A', 'B', 'C', 'D'], [1, 2, 3, 4], [10, 20, 30, 40]]
>>> list(zip(*exampleList))
[('A', 1, 10), ('B', 2, 20), ('C', 3, 30), ('D', 4, 40)]

Edit:

If you want your output to be a list of lists, instead of a list of tuples,

[list(i) for i in zip(*empampleList)]

should do the trick