Enumerating the Cartesian product

The term Cartesian product refers to the idea of enumerating all the possible combinations of elements drawn from a number of sets.

Mathematically, we might say that the product of two sets,, has 52 pairs, as follows:

{(1, C), (1, D), (1, H), (1, S),  (2, C), (2, D), (2, H), (2, S), ...,  (13, C), (13, D), (13, H), (13, S)}

We can produce the preceding results by executing the following commands:

>>> list(product(range(1, 14), '♣♦♥♠'))
[(1, '♣'), (1, '♦'), (1, '♥'), (1, '♠'),  (2, '♣'), (2, '♦'), (2, '♥'), (2, '♠'),...  (13, '♣'), (13, '♦'), (13, '♥'), (13, '♠')]

The calculation of a product can be extended ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.