Simple way, with a library call:
import itertools
def lists(n):
return itertools.product(xrange(n), repeat=n)
This returns an iterator, rather than a list. You can get a list if you want by calling list
on the result.
If you want to do this without foisting the job onto itertools
, you can count in base n
, incrementing the last digit and carrying whenever you hit n
:
def lists(n):
l = [0]*n
while True:
yield l[:]
for i in reversed(xrange(n)):
if l[i] != n-1:
break
l[i] = 0
else:
# All digits were n-1; we're done
return
l[i] += 1