• Skip to primary navigation
  • Skip to main content

The Programming Expert

Solving All of Your Programming Headaches

  • Home
  • Learn to Code
    • Python
    • JavaScript
  • Code Snippets
    • HTML
    • JavaScript
    • jQuery
    • PHP
    • Python
    • SAS
    • Ruby
  • About
  • Write for Us
You are here: Home / Python / Cartesian Product of Two Lists in Python

Cartesian Product of Two Lists in Python

March 3, 2022 Leave a Comment

In Python, we can get the Cartesian product of two lists easily. The easiest way to obtain the Cartesian product of two lists is with list comprehension.

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

cartesian_product = [(x,y) for x in list1 for y in list2]

print(cartesian_product)

#Output:
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]

You can also use a for loop to get the Cartesian product of two list objects in Python.

list1 = ["a", "b"]
list2 = [1, 2]

def cartesian_product(lst1, lst2):
    result = []
    for x in lst1:
        for y in lst2:
            result.append((x,y))
    return result

print(cartesian_product(list1,list2))

#Output:
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]

Finally, the Python itertools module has a function product() which finds Cartesian products for you.

from itertools import product

list1 = ["a", "b"]
list2 = [1, 2]

print(list(product(list1,list2)))

#Output:
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]

When working with collections of data in Python, the ability to manipulate them and create new collections is very valuable.

One such manipulation is the ability to get the Cartesian product of lists in a new list.

The Cartesian product of two sets A and B is the set of all possible ordered pairs (a, b), where a is in A and b is in B. We can get the Cartesian product between two lists easily with Python.

The easiest way to get the Cartesian product of two lists is with list comprehension.

Below is a simple example of how to find the Cartesian product of two lists in Python using list comprehension.

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

cartesian_product = [(x,y) for x in list1 for y in list2]

print(cartesian_product)

#Output:
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]

Using for Loop to Get Cartesian Product of Lists in Python

We can also use a loop to get the Cartesian product of lists in Python.

By definition, the Cartesian product of two collections of elements are all possible ordered pairs.

We can define a loop easily which will loop over all possible combinations of our lists and create ordered pairs in the form of tuples.

Below is a simple example of how to find the Cartesian product of two lists in Python using iteration.

list1 = ["a", "b"]
list2 = [1, 2]

def cartesian_product(lst1, lst2):
    result = []
    for x in lst1:
        for y in lst2:
            result.append((x,y))
    return result

print(cartesian_product(list1,list2))

#Output:
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]

Using itertools product() Function to Get Cartesian Product of Lists in Python

The itertools module has many great functions which allow us to iterate over collections and perform complex tasks easily.

We can use the itertools product() function to calculate the Cartesian product of lists.

To get the Cartesian product of multiple lists in Python using product(), just pass the lists to the function.

Below is a simple example of how to find the Cartesian product of two lists in Python using itertools and product().

from itertools import product

list1 = ["a", "b"]
list2 = [1, 2]

print(list(product(list1,list2)))

#Output:
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]

Hopefully this article has been useful for you to learn how to get the cartesian product of lists in Python.

Other Articles You'll Also Like:

  • 1.  Check if String Contains Numbers in Python
  • 2.  How to Check If Value is in List Using Python
  • 3.  Drop Last n Rows of pandas DataFrame
  • 4.  Python Even or Odd – Check if Number is Even or Odd Using % Operator
  • 5.  pandas product – Get Product of Series or DataFrame Columns
  • 6.  Find All Pythagorean Triples in a Range using Python
  • 7.  Calculate Distance Between Two Points in Python
  • 8.  Get Length of File Using Python
  • 9.  Truncate String in Python with Slicing
  • 10.  PROC PHREG Equivalent in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · The Programming Expert · About · Privacy Policy