﻿ Python: Generate all permutations of a list in Python - w3resource

# Python: Generate all permutations of a list in Python

## Python List: Exercise - 18 with Solution

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.

Pictorial Presentation Sample Solution:

Python Code:

``````import itertools
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: ## Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Capitalizes the first letter of a string:

Example:

```def tips_capitalize(s, lower_rest=False):
return s[:1].upper() + (s[1:].lower() if lower_rest else s[1:])
print(tips_capitalize('pythonTips'))
print(tips_capitalize('pythonTips', True))
```

Output:

```PythonTips
Pythontips
```

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook