Some thougts on cartesian products

Bryan Olson fakeaddress at
Mon Jan 23 13:00:14 EST 2006

Steven D'Aprano wrote:
> 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.

Query languages have included Cartesian product for decades. Their
solution is to optimize expressions to avoid building, or even
iterating over, big Cartesian products.

>>>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.

It keeps coming up in exercises and examples. How many of your
Google results note an application that actually calls for a
Cartesian product enumerator? I wrote one an old thread, and so
far I've written it one more time than I've used it.


More information about the Python-list mailing list