Search code examples
pythonpython-itertools

Why reading/unpacking data from itertools.permutation changed its attribute/content?


I am trying to use the permutation feature from itertools, then I noticed. If I try to unpack/read the data from permutation, it changes some attribute info

from itertools import permutations

a = permutations('abc')


print(('a', 'b', 'c') in a)

for x in a:
    print(x)

print(('a', 'b', 'c') in a)

for x in a:
    print(x)

Output:

True

('a', 'c', 'b')
('b', 'a', 'c')
('b', 'c', 'a')
('c', 'a', 'b')
('c', 'b', 'a')

False

How come does this happen? I checked out the official page, and cannot find any clue. My environment is pycharm with python 3.7.4


Solution

  • As others aready said, the problem is that a is not a list, but a generator; that is, a sequence that gets used up as you iterate over it -- hence you can only iterate over it once.

    If you look carefully, you'll see that your first print loop only printed five of the six permutations; the first permutation disappeared when you checked it against ('a', 'b', 'c') in your first print statement. The for-loop then prints out what's left, and the rest of your code is trying to drink from an empty cup.

    To get the behavior you expect, make a into a list like this:

    a = list(permutations('abc'))
    

    And when you get a chance, read up on generators, iterators, and "comprehensions"; they're everywhere in Python (often hidden in plain sight), and they're great.