Understand itertools.permutations(): Create a Permutation From an Iterable – Python Tutorial

By | December 27, 2021

In this tutorial, we will introduce how to create a permutation from a iterable in python. We will use itertools.permutations() to implement it.

Permutation

In mathematics, permutation is defined as:

\(P(n,r)=\frac{n!}{(n-r)!}\)

itertools.permutations()

In python, itertools.permutations() is defined as:

p[, r]

r-length tuples, all possible orderings, no repeated elements.

We will use an example to show you how to use it.

For example:

data = 'ABCD'
p = itertools.permutations(data)
for x in p:
    print(x)

Run this code, you will get a permutation.

('A', 'B', 'C', 'D')
('A', 'B', 'D', 'C')
('A', 'C', 'B', 'D')
('A', 'C', 'D', 'B')
('A', 'D', 'B', 'C')
('A', 'D', 'C', 'B')
('B', 'A', 'C', 'D')
('B', 'A', 'D', 'C')
('B', 'C', 'A', 'D')
('B', 'C', 'D', 'A')
('B', 'D', 'A', 'C')
('B', 'D', 'C', 'A')
('C', 'A', 'B', 'D')
('C', 'A', 'D', 'B')
('C', 'B', 'A', 'D')
('C', 'B', 'D', 'A')
('C', 'D', 'A', 'B')
('C', 'D', 'B', 'A')
('D', 'A', 'B', 'C')
('D', 'A', 'C', 'B')
('D', 'B', 'A', 'C')
('D', 'B', 'C', 'A')
('D', 'C', 'A', 'B')
('D', 'C', 'B', 'A')

If r = 2, you will get:

p = itertools.permutations(data, r = 2)

for x in p:
    print(x)

You will get:

('A', 'B')
('A', 'C')
('A', 'D')
('B', 'A')
('B', 'C')
('B', 'D')
('C', 'A')
('C', 'B')
('C', 'D')
('D', 'A')
('D', 'B')
('D', 'C')

Leave a Reply