variable X procuct - [(x,y) for x in list1 for y in list2]

Jeff Epler jepler at unpythonic.net
Tue May 28 17:11:06 EDT 2002


On Tue, May 28, 2002 at 08:42:17PM +0000, steindl fritz wrote:
> hi list,
> 
> first - maybe sombody can help me with the english expression for the 
> german word 'kreuzprodukt' - this my question is dealing with

"cross-product" or "cartesian product", I think.

In Python 2.2, the following code seems to work:
def cross(l=None, *args):
    if l is None:
	# The product of no lists is 1 element long,
	# it contains an empty list
	yield []
	return
    # Otherwise, the product is made up of each 
    # element in the first list concatenated with each of the
    # products of the remaining items of the list
    for i in l:
	for j in cross(*args):
	    yield [i] + j 

for i in cross("12", "abc", "xyzw"): print i

before generators, you'd have to write the code in a slightly different
way...

Jeff





More information about the Python-list mailing list