- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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)]
- Related Articles
- Python - Generate all possible permutations of words in a Sentence
- Generating all possible permutations of array in JavaScript
- How to find all possible permutations of a given string in Python?
- Creating all possible unique permutations of a string in JavaScript
- How to generate all permutations of a list in Python?
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Print first n distinct permutations of string using itertools in Python
- Python Program to print all permutations of a given string
- Python - Find starting index of all Nested Lists
- Python program to get all permutations of size r of a string
- Permutations in Python
- Print all permutations of a string in Java
- Program to count average of all special values for all permutations of a list of items in Python
- Print all permutations of a given string
- All permutations of a string using iteration?

Advertisements