← All lessons

itertools: combinations

Sign in · Sign up

Lesson 11.10

itertools gives ready-made combinatorics:

from itertools import combinations, permutations, product

print(list(combinations(players, 2)))   # pairs regardless of order
print(list(permutations(players, 2)))   # pairs where order matters
print(list(product(["yes", "no"], repeat=2)))
  • combinations — "Mia and Timur" and "Timur and Mia" are the same thing;
  • permutations — those are two different options;
  • product takes one item from each list.

All of them return an iterator, so list(...) is needed for printing.

The check sets the names players. Print three lines: all pairs of two without repeats, all permutations of two, and how many there are in total — with len.

Hint

combinations ignores the order, permutations takes it into account.

Both return an iterator, so list(...) is needed for printing. There are more permutations than combinations — len shows the difference.