Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Pythonic way to get a list of tuples of all the possible combinations of the elements of two lists?

Tags:

python

list

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.

like image 921
ptomato Avatar asked Nov 29 '22 19:11

ptomato


1 Answers

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')]
like image 153
Moe Avatar answered Dec 05 '22 14:12

Moe