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.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With