views:

135

answers:

2

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.

+10  A: 

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
Beat me to it. +1.
danben
+1 i love this pythonic solution.
systempuntoout
+8  A: 

Try itertools.product.

Alexander Gessler
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
Before I write any code, I always look into the Python standard library, such as operator, itertools, functools and collections.
Selinap