How to Use itertools.permutations in Python: Simple Guide
Use
itertools.permutations(iterable, r) to get all possible ordered arrangements of length r from the iterable. If r is omitted, it defaults to the length of the iterable, producing full-length permutations.Syntax
The itertools.permutations function has this syntax:
itertools.permutations(iterable, r=None)
Here:
- iterable: any sequence like a list, string, or tuple to permute.
- r: optional length of each permutation; if not given, it uses the full length of the iterable.
The function returns an iterator of tuples, each tuple is one permutation.
python
import itertools perms = itertools.permutations(['a', 'b', 'c'], 2) for p in perms: print(p)
Output
('a', 'b')
('a', 'c')
('b', 'a')
('b', 'c')
('c', 'a')
('c', 'b')
Example
This example shows how to get all permutations of the letters in the word "dog" with length 3 (full length). It prints each permutation as a string.
python
import itertools word = 'dog' permutations = itertools.permutations(word) for p in permutations: print(''.join(p))
Output
dog
dgo
god
gdo
odg
god
Common Pitfalls
Some common mistakes when using itertools.permutations:
- Forgetting that the result is an iterator, so you can only loop once unless you convert it to a list.
- Not specifying
rwhen you want shorter permutations, which defaults to full length. - Trying to modify the tuples returned (they are immutable).
Example of a wrong approach and the fix:
python
# Wrong: trying to reuse iterator import itertools perms = itertools.permutations([1, 2, 3]) print(list(perms)) # works first time print(list(perms)) # prints [] because iterator is exhausted # Right: convert to list once perms = list(itertools.permutations([1, 2, 3])) print(perms) print(perms)
Output
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
[]
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
Quick Reference
Summary tips for using itertools.permutations:
- Use
permutations(iterable, r)to get ordered arrangements of lengthr. - Result is an iterator of tuples; convert to list if you need to reuse.
- Tuples are immutable; convert to list if you want to modify.
- Works with any iterable: strings, lists, tuples.
Key Takeaways
Use itertools.permutations to generate all ordered arrangements of elements from an iterable.
The second argument r controls the length of each permutation; it defaults to the iterable's length.
The function returns an iterator of tuples, so convert to list to reuse or inspect multiple times.
Tuples returned are immutable; convert to list if you need to change elements.
Works with any iterable like strings, lists, or tuples.