w3resource

Python: Generate all permutations of a list in Python


Generate All List Permutations

Write a Python program to generate all permutations of a list in Python.

In mathematics, the notion of permutation relates to the act of arranging all the members of a set into some sequence or order, or if the set is already ordered, rearranging (reordering) its elements, a process called permuting. These differ from combinations, which are selections of some members of a set where order is disregarded.

In the following image each of the six rows is a different permutation of three distinct balls.

Visual Presentation:

Different permutation of three distinct balls

Sample Solution:

Python Code:

# Import the 'itertools' module, which provides various functions for working with iterators
import itertools

# Use 'itertools.permutations' to generate all permutations of the list [1, 2, 3], and convert the result to a list
# This will produce all possible orderings of the elements in the list
print(list(itertools.permutations([1, 2, 3])))

Sample Output:

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] 

Explanation:

In the above exercise -

import itertools  -> Import the itertools module.

list(itertools.permutations([1,2,3])): Generate all permutations of the list [1,2,3] using the permutations() function from the itertools module. The permutations() function returns an iterator, so we need to convert it to a list to print it.

Flowchart:

Flowchart: Generate all permutations of a list in Python

Python Code Editor:

Previous: Check if each number is prime in a list of numbers.
Next: Difference between the two lists.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.