tags:

views:

198

answers:

4
l1 = [4, 6, 8]
l2 = [a, b, c]

result = [(4,a),(6,b),(8,c)]

How do I do that?

+12  A: 

The zip standard function does this for you:

>>> l1 = [4, 6, 8]
>>> l2 = ["a", "b", "c"]
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]

If you're using Python 3.x, then zip returns a generator and you can convert it to a list using the list() constructor:

>>> list(zip(l1, l2))
[(4, 'a'), (6, 'b'), (8, 'c')]
Greg Hewgill
+9  A: 

Use zip(l1, l2).

l1 = [1, 2, 3]
l2 = [4, 5, 6]
>>> zip(l1, l2)
[(1, 4), (2, 5), (3, 6)]

Note that if your lists are of different lengths, the result will be truncated to the length of the shortest input.

>>> print zip([1, 2, 3],[4, 5, 6, 7])
[(1, 4), (2, 5), (3, 6)]

You can also use zip with more than two lists:

>>> zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

If you have a list of lists, you can call zip using an asterisk:

>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*l)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
Mark Byers
+1  A: 
>>> l1 = [4, 6, 8]; l2 = ['a', 'b', 'c']
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]
Peter
A: 

If the lists are the same length, or if you want the length of the list to be the length of the shorter list, then use zip, as other people have pointed out.

If the lists are different lengths, then you can use map with a transformation function of None:

>>> l1 = [1, 2, 3, 4, 5]
>>> l2 = [9, 8, 7]
>>> map(None, l1, l2)
[(1, 9), (2, 8), (3, 7), (4, None), (5, None)]

Note that the 'extra' values get paired with None.

It's also worth noting that both zip and map can be used with any number of iterables:

>>> zip('abc', 'def', 'ghi')
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> map(None, 'abc', 'def', 'gh')
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', None)]
Edward Loper