All possible permutations of N lists in Python


If we have two lists and we need to combine each element of the first element with each element of the second list, then we have the below approaches.

Using For Loop

In this straight forward approach we create a list of lists containing the permutation of elements from each list. we design a for loop within another for loop. The inner for loop refers to the second list and Outer follow refers to the first list.

Example

 Live Demo

A = [5,8]
B = [10,15,20]

print ("The given lists : ", A, B)
permutations = [[m, n] for m in A for n in B ]

Output

Running the above code gives us the following result:

The given lists : [5, 8] [10, 15, 20]
permutations of the given values are : [[5, 10], [5, 15], [5, 20], [8, 10], [8, 15], [8, 20]]

Using itertools

The itertools module has a iterator named product. It does the same thing what the above nested for loop does. Creates nested for loops internally to give the required product.

Example

 Live Demo

import itertools

A = [5,8]
B = [10,15,20]

print ("The given lists : ", A, B)
result = list(itertools.product(A,B))
print ("permutations of the given lists are : " + str(result))

Output

Running the above code gives us the following result:

The given lists : [5, 8] [10, 15, 20]
permutations of the given values are : [(5, 10), (5, 15), (5, 20), (8, 10), (8, 15), (8, 20)]

Updated on: 07-Jan-2020

697 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements