HelloWorld
HelloWorld

Reputation: 93

Optimizing itertools permutations in Python

In context of memory management i face a lot of issues while using itertools permutations specially when the length of list is more than 10.

Is there any better way of generating permutations for any list such that memory is not much utilized ?

Below is the way how i am using it.

     num_list = [i for i in range(0,18)]
     permutation_list = list(permutations(num_list,len(num_list)))

     for p_tuples in permutation_list:
          print(p_tuples)

Upvotes: 3

Views: 2768

Answers (2)

Dmitry Rubanovich
Dmitry Rubanovich

Reputation: 2627

permutations returns a generator. So the solution is pretty much what you already wrote:

num_list = [i for i in range(0,18)]

for p_tuples in permutations(num_list,len(num_list)):
    print(p_tuples)

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251373

If all you need to do is iterate over the permutations, don't store them. Iterate directly over the object returned by itertools.permutations. In other words do this:

permutations = permutations(num_list,len(num_list))
for perm in permutations:
    doSomethingWith(perm)

Calling list on an iterator is exactly the way to say "give me all of the elements right now in memory at the same time". If you don't want or need all of them in memory at once, don't use list. If you just want to use one element at a time, just iterate over what you want to iterate over.

Note that your code will still take a long time to run if you really try to go through all the permutations, because 18! is a really big number.

Upvotes: 3

Related Questions