Pattern for permutations?

Tim Churches tchur at optushome.com.au
Sat Apr 6 18:06:27 EST 2002


This may be an elementary question but the solution is
not obvious to me.

I want to define a function which takes as its argument a
list which contains one or more sequences, and then does stuff
with every permutation of the elements of those sequences. For
example, a function which works for a list containing three
sequences:

def nestedloops(list_of_sequences):
	for element0 in list_of_sequences[0]:
		for element1 in list_of_sequences[1]:
			for element2 in list_of_sequences[2]:
				# do stuff with each permutation
				print element0, element1, element2

nestedloops([(1,2,3),('one','two','three'),('isa','dalawa','tatlo')])

How does one generalise such a function so that it handles any number 
of sequences in the passed list of sequences i.e. a dynamic number of
levels of nesting? 

It occurred to me that the function could emit dynamic code for the 
"for" loops and then eval() that, but that seems a bit messy and
possibly slow.

Is there a better way?

Tim C





More information about the Python-list mailing list