1
I am running the following code in google colab notebook
from itertools import permutations

p = permutations([1, 2, 3])
print(list(p))

for i in list(p):
  print(i)

In the above code first, print(list(p)) statement prints but second print(i) does not show any result.

Can anyone know the reason why this is happening?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
SUMIT JHA
  • 33
  • 6
  • interesting, I believe it's because you already consume the iterator `p` the first time you call `list(p)` – rv.kvetch Sep 19 '21 at 16:04
  • 1
    try assigning the value to a variable like `L = list(p)` and then iterating over `L` - that should work in this case – rv.kvetch Sep 19 '21 at 16:05

1 Answers1

3

p is an iterator. It can only be consumed once. Since the 1st list(p) already consumes it, the 2nd list(p) will give an empty list. If you need to consume it multiple times, you need to materialize it as a list:

p = list(permutations([1, 2, 3]))
print(p)

for i in p:
  print(i)

[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Psidom
  • 209,562
  • 33
  • 339
  • 356