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

Suppose I have two lists of different sizes

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

What is the Pythonic way to get a list of tuples of call possible combinations of one element from aand one element from b?

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

The order of the elements in cdoes not matter.

A two-cycle solution is fortrivial, but it does not look like Pythonic.

+3
source share
2 answers

Give it a try itertools.product.

+9
source

Use 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')]
+13
source

Source: https://habr.com/ru/post/1737145/


All Articles