• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
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.  Python sin – Find Sine of Number in Radians Using math.sin()
  • 2.  Get Username in Python using os module
  • 3.  How to Multiply Two Numbers in Python
  • 4.  Python cosh – Find Hyperbolic Cosine of Number Using math.cosh()
  • 5.  Squaring in Python – Square a Number Using Python math.pow() Function
  • 6.  How to Rotate String in Python
  • 7.  Check if List is Subset of Another List in Python
  • 8.  Check if String Does Not Contain Substring in Python
  • 9.  Using Python to Convert Integer to String with Leading Zeros
  • 10.  Get Month Name from Datetime in pandas DataFrame

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 *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

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