Itertools Combinations in Python

Level 3116 keystrokes

This generates all 2-element combinations from a list.

Python code

# combinations() picks items where order does not matter
1from itertools import combinations
2
# Four items to choose from
3items = ["A", "B", "C", "D"]
# Every pair of 2 different items, each pair once: C(4,2) = 6 tuples
# ("A", "B") is included but ("B", "A") is not
4combos = list(combinations(items, 2))
# Prints [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
5print(combos)

Output

[('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 8
  • ,× 4
  • (× 3
  • )× 3
  • =× 2
  • [× 1
  • ]× 1

More Python examples at level 3

← Python typing practice