2

Possible Duplicate:
Python - merge items of two lists into a list of tuples

How do I merge two lists in a nested way?

Eg:

list1 = a,b,c

list2 = d,e,f

I want the output to be:

[[a,d][b,e][c,f]]
Community
  • 1
  • 1
Bob
  • 29
  • 1
  • 1
  • 2

2 Answers2

16

Just zip them:

>>> l1 = ['a', 'b', 'c']
>>> l2 = ['d', 'e', 'f']
>>> zip(l1, l2)
[('a', 'd'), ('b', 'e'), ('c', 'f')]

If you need lists, not tuples, in the result:

>>> [list(l) for l in zip(l1, l2)]
[['a', 'd'], ['b', 'e'], ['c', 'f']]
Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
5

Direct copy and paste from book:

The zip function

Sometimes it’s useful to combine two or more iterables before looping over them. The zip function will take the corresponding elements from one or more iterables and combine them into tuples until it reaches the end of the shortest iterable:

>>> x = [1, 2, 3, 4]
>>> y = ['a', 'b', 'c']
>>> z = zip(x, y)
>>> list(z)
[(1, 'a'), (2, 'b'), (3, 'c')]
Mr.Python
  • 141
  • 1
  • 6