Some thougts on cartesian products

Steven D'Aprano steve at
Mon Jan 23 11:57:45 CET 2006

On Mon, 23 Jan 2006 10:36:55 +0000, Bryan Olson wrote:

> Christoph Zwerschke wrote:
> [...]
>> That may be the main problem to decide whether the cartesian product 
>> should return a generator or a list.
> The Cartesion product is a set.

And the generalization of mathematical sets in Python can be built-in
sets, lists or tuples, depending on what you need.

Given that cartesian products tend to be *extremely* large, some sort of
iterator is the only practical solution -- even if that's not
mathematically pure.

> [...]
>> That's the other problem. The uses cases (like the password cracker 
>> example) are very limited and in these cases you can either write nested 
>> loops or write your own cartesian product.
> Cartesian product is one of the essential operations of
> relational algebra; in that context it's widely useful.
> By itself, it's usually not what one wants.

Google on "Cartesian product python" and you will find thousands of hits.
This is something that keeps coming up over and over again.

Personally, I think cartesian products, together with permutations and
combinations, belong in a module, not built-ins.


More information about the Python-list mailing list