4

Suppose I have two differently-sized lists

a = [1, 2, 3]
b = ['a', 'b']

What is a Pythonic way to get a list of tuples c of all the possible combinations of one element from a and one element from b?

>>> print c
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]

The order of elements in c does not matter.

The solution with two for loops is trivial, but it doesn't seem particularly Pythonic.

ptomato
  • 56,175
  • 13
  • 112
  • 165
  • Here are some duplicates: http://stackoverflow.com/questions/1663807/how-can-i-iterate-through-two-lists-in-parallel-in-python-closed, http://stackoverflow.com/questions/126524/iterate-a-list-as-tuples-in-python, http://stackoverflow.com/questions/1210396/how-do-i-iterate-over-the-tuples-of-the-items-of-two-or-more-lists-in-python – Nathan Fellman Mar 16 '10 at 13:28
  • 2
    @Nathan Fellman - actually, none of those are duplicates. Please read more carefully before voting to close. – danben Mar 16 '10 at 13:30
  • I must've missed the difference. Is this different because the lists are different length? – Nathan Fellman Mar 16 '10 at 13:32
  • @Nathan Fellman, not only that, but `zip` returns tuples of `(a[0], b[0])`, `(a[1], b[1])`, etc. I want tuples of every possible combination of elements of `a` and `b`. – ptomato Mar 16 '10 at 13:46
  • @danben, you're absolutely right. My apologies. – Nathan Fellman Mar 16 '10 at 15:19

2 Answers2

13

Use a list comprehension:

>>> a = [1, 2, 3]
>>> b = ['a', 'b']
>>> c = [(x,y) for x in a for y in b]
>>> print c
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
Moe
  • 28,607
  • 10
  • 51
  • 67
10

Try itertools.product.

Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122
  • 1
    Thanks. Both this and @Moe's answer seem equally valid, so I'm arbitrarily deciding to accept this one because a generator is more useful at this specific point in my code. +1 for both. – ptomato Mar 16 '10 at 13:51
  • Before I write any code, I always look into the Python standard library, such as operator, itertools, functools and collections. – riza Mar 16 '10 at 15:02