Itertools Product in Python

Level 3121 keystrokes

This computes the Cartesian product of two lists.

Python code

# product() builds the Cartesian product of iterables
1from itertools import product
2
# Two colors
3colors = ["R", "G"]
# Two sizes
4sizes = ["S", "M"]
# Pairs every color with every size: 2 × 2 = 4 tuples, like nested for loops
5combos = list(product(colors, sizes))
# Prints [('R', 'S'), ('R', 'M'), ('G', 'S'), ('G', 'M')]
6print(combos)

Output

[('R', 'S'), ('R', 'M'), ('G', 'S'), ('G', 'M')]
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
  • ,× 3
  • (× 3
  • )× 3
  • =× 3
  • [× 2
  • ]× 2

More Python examples at level 3

← Python typing practice