range()
and permutation()
both return generators that generate items on demand. You don't need to call list()
and turn them into lists. Just iterate over them directly and access the items one by one.
num = 11
base = range(1, num+1)
permutations = itertools.permutations(base)
for permutation in permutations:
# Do something with `permutation`.
(Note that a generator can only be used once. If you want to iterate over the permutations more than once you'll need to call itertools.permutations()
multiple times.)
To stop after n items use itertools.islice()
:
for permutation in itertools.islice(permutations, n):
# Do something with `permutation`.
You can skip items at the beginning, too. This would skip the first five permutations:
for permutation in itertools.islice(permutations, 5, n):
# Do something with `permutation`.
If you want to count the permutations you can add enumerate()
, which attaches an index to every entry:
for i, permutation in enumerate(itertools.islice(permutations, n)):
# Skip the fifth permutation.
if i == 4:
continue
# Do something with `permutation`.
By the way, please use lowercase for variable names. Only class names should be capitalized.