Search code examples
pythonpermutationpython-itertools

Python Itertools Permutations


I am currently writing a program that uses itertools, and one piece of it does not seems to functioning properly. I would like the input that determines the length of the lists the permutation function outputs to be equal to length of the list from which it generates its outputs. In other words, I have

import itertools

b = 0
c = 9
d = [0,1,2]
e = len(d)


while b < c:
        d.append(b)
        b = b+1

print([x for x in itertools.permutations(d,e)])

And I would like this to generate all the possible permutations of d that are equal to this length. I have been experimenting with this and it seems that second determiner must be an integer. I even tried making a new variable, f, and having f = int(e) and then replacing e with f in the print statement, but with no success. With either of these all I got was [()]

Thanks for your help.


Solution

  • You need to set e after you build the list. len(d) returns a value, not a reference to the list's length.

    d = range(0,9)  # build an arbitrary list here
                    # this creates a list of numbers: [0,1,2,3,4,5,6,7,8]
    e = len(d)
    print list(itertools.permutations(d, e))
    

    Note that the number of permutations is very large, so storing all of them in a list will consume large amounts of memory - you'd be better off with this:

    d = range(0,9)
    e = len(d)
    for p in itertools.permutations(d, e):
        print p