If I make any operation on an object, it is nullified after. Why is it so? Looks like list() method is doing it.
from itertools import permutations
my_string = 'ada'
result = permutations(my_string)
result2 = permutations(my_string)
print(result)
print('Number of variations is: ', len(list(result)))
print(list(result))
print(' ')
print(result)
print('Number of variations is: ', len(list(result)))
print(list(result))
The first three attempts to print() the object are a success.
<itertools.permutations object at 0x0000015B4B4555E0>
Number of variations is: 6
[('a', 'd', 'a'), ('a', 'a', 'd'), ('d', 'a', 'a'), ('d', 'a', 'a'), ('a', 'a', 'd'), ('a', 'd', 'a')]
The second attempt to print() them gives Null.
<itertools.permutations object at 0x0000015B4B4555E0>
Number of variations is: 0
[]
CodePudding user response:
You cannot iterate multiple times through the result of itertools.permutations(). From the results you are showing, it looks like you have done:
result = permutations(my_string)
len(list(result))
len(list(result))
An iterator can be used once and only once. If you need to iterate through the permutation a second time, either call permuations()
again, or hold onto list(result)
.
I noticed that you printed the value of the iterator, and both times is showed the exact same iterator.
CodePudding user response:
itertools.permutations
returns an iterator. Iterators can only be looped over once.
After you do list(result)
, the result
iterator is exhausted and thus len(result)
will be 0.
I also assume you made a mistake while copying the output since when you actually run the code, only the first call(len(list(result))
) gives the expected output.