Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
All possible permutations of N lists in Python
When we have multiple lists and need to combine each element from one list with each element from another list, we're creating what's called a Cartesian product (not permutations). Python provides several approaches to achieve this combination.
Using List Comprehension
This straightforward approach uses nested list comprehension to create all possible combinations. The outer loop iterates through the first list, while the inner loop iterates through the second list ?
Example
A = [5, 8]
B = [10, 15, 20]
print("The given lists:", A, B)
combinations = [[m, n] for m in A for n in B]
print("Combinations of the given values are:", combinations)
Output
The given lists: [5, 8] [10, 15, 20] Combinations of the given values are: [[5, 10], [5, 15], [5, 20], [8, 10], [8, 15], [8, 20]]
Using itertools.product()
The itertools.product() function provides a more elegant solution for creating Cartesian products. It internally creates nested loops to generate all possible combinations ?
Example
import itertools
A = [5, 8]
B = [10, 15, 20]
print("The given lists:", A, B)
result = list(itertools.product(A, B))
print("Combinations of the given lists are:", result)
Output
The given lists: [5, 8] [10, 15, 20] Combinations of the given lists are: [(5, 10), (5, 15), (5, 20), (8, 10), (8, 15), (8, 20)]
Working with Multiple Lists
Both approaches can handle more than two lists. Here's an example with three lists ?
import itertools
A = [1, 2]
B = ['x', 'y']
C = [10, 20]
# Using itertools.product()
result = list(itertools.product(A, B, C))
print("Three-list combinations:", result)
Three-list combinations: [(1, 'x', 10), (1, 'x', 20), (1, 'y', 10), (1, 'y', 20), (2, 'x', 10), (2, 'x', 20), (2, 'y', 10), (2, 'y', 20)]
Comparison
| Method | Output Type | Best For |
|---|---|---|
| List Comprehension | Lists | Simple cases, readable syntax |
itertools.product() |
Tuples | Multiple lists, memory efficiency |
Conclusion
Use itertools.product() for creating Cartesian products of multiple lists as it's more efficient and handles any number of lists. List comprehension works well for simple two-list combinations when you need the result as lists.
