Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian product of two lists in python

Tags:

python

Cartesian product of two lists in python

list1 = ['a', 'b']
list2 = [1, 2, 3, 4, 5]

Expected Output:

list3 = ['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'b5']
like image 345
mohsen h Avatar asked Sep 05 '18 20:09

mohsen h


People also ask

How do you code a Cartesian product in Python?

Get Cartesian Product in Python Using the itertools ModuleThe product(*iterables, repeat=1) method of the itertools module takes iterables as input and returns their cartesian product as output. The cartesian product order will be the order of each set/list in the provided argument iterables .

How do you find the Cartesian product for a list set?

The Cartesian square of a set X is the Cartesian product X2 = X × X. An example is the 2-dimensional plane R2 = R × R where R is the set of real numbers: R2 is the set of all points (x,y) where x and y are real numbers (see the Cartesian coordinate system).

What is the Cartesian product of two sets?

In mathematics, the Cartesian Product of sets A and B is defined as the set of all ordered pairs (x, y) such that x belongs to A and y belongs to B. For example, if A = {1, 2} and B = {3, 4, 5}, then the Cartesian Product of A and B is {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}.


3 Answers

If you are using Python 3.6+ you can use f-strings as follows:

list3 = [f'{a}{b}' for a in list1 for b in list2]

I really like this notation because it is very readable and matches with the definition of the cartesian product.

If you want more sophisticated code, you could use itertools.product:

import itertools

list3 = [f'{a}{b}' for a, b in itertools.product(list1, list2)]

I checked the performance, and it seems the list comprehension runs faster than the itertools version.

like image 190
lmiguelvargasf Avatar answered Oct 13 '22 06:10

lmiguelvargasf


Do a list comprehension, iterate over both the lists and add the strings, like

list3 = [i+str(j) for i in list1 for j in list2]
like image 15
Raunaq Jain Avatar answered Oct 13 '22 07:10

Raunaq Jain


You could use itertools.product function:

from itertools import product

list3 = [a+str(b) for a, b in product(list1, list2)]
like image 5
miindlek Avatar answered Oct 13 '22 06:10

miindlek