Search code examples
pythonpermutation

Python Permutations unexpected behavior?


Given the sample below:

from itertools import permutations
p=permutations("abc", 2)

def func():
  for i in p:
      print("values=", i)
        

print("First use case:") 
func()

print("Second use case:") 
func()

print("The End!")

Output:

First use case:
values= ('a', 'b')
values= ('a', 'c')
values= ('b', 'a')
values= ('b', 'c')
values= ('c', 'a')
values= ('c', 'b')
Second use case:
The End!

The question is about the second function CALL, why doesn't print the values?!


Solution

  • p is and iterator which means once you finish iterating through it there are no more elements in it. You will have to regenerate the iterator.

    Like:

    def func():
      p=permutations("abc", 2)
      for i in p:
          print("values=", i)
    

    If you have situation where the iterator is generated randomly and you want to use the same random elements then you will have to move them to something like a list.

    Example:

    from numpy.random import permutation
    import numpy as np
    p =  list(iter(np.random.randint(0,10,10)))
    
    def func():
      for i in p:
          print("values=", i)