list of all possible values
David Gibb
degibb at gmail.com
Mon Jul 13 12:21:37 EDT 2009
Hi guys.
I was thinking about a problem I had: suppose I have a list of
possible values. I want to to have a list of all possible lists of
length n whose values are in that original list.
For example: if my values are ['a', 'b', 'c'], then all possible lists
of length 2 would be: aa, ab, ac, ba, bb, bc, ca, cb, cc.
I created a recursive program to do it, but I was wondering if there
was a better way of doing it (possibly with list comprehensions).
Here's my recursive version:
vals = ['a', 'b', 'c']
def foo(length):
if length <=0:
return []
if length == 1:
return [[x] for x in vals]
else:
return [x + [y] for x in foo(length - 1) for y in vals]
print foo(3)
Thanks,
David
More information about the Python-list
mailing list