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.
Advertisement
Answer
>>> 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