10. Combinations of a list
Create combinations from a list of items.
The standard iterator says exactly what mathematical operation is happening, which is easier to recognize than nested loops whose only purpose is pair or tuple generation. It also generalizes cleanly as the combination size changes.
10.1. Don’t do this
1symbols = ['A', 'B', 'C', 'D']
2
3combs = []
4
5for i, symbol_i in enumerate(symbols):
6 for j, symbol_j in enumerate(symbols):
7 if i < j:
8 tup = symbol_i, symbol_j
9 combs.append(tup)
10.2. Do this
1from itertools import combinations
2
3symbols = ['A', 'B', 'C', 'D']
4
5combs = list(combinations(symbols, 2))