Looking at this answer, it seems that using a list comprehension (or for loop with append) is equivalent to calling list(..) on an iterator. Since generators are iterators too, I'd expect the same for generators. However, if you run
def permute(xs, count, low = 0):
if low + 1 >= count:
yield xs
else:
for p in permute(xs, low + 1):
yield p
for i in range(low + 1, count):
xs[low], xs[i] = xs[i], xs[low]
for p in permute(xs, low + 1):
yield p
xs[low], xs[i] = xs[i], xs[low]
print("Direct iteration")
for x in permute([1, 2], 2):
print(x)
print("Listing")
for x in list(permute([1, 2], 2)):
print(x)
Direct iteration
[1, 2]
[2, 1]
Listing
[1, 2]
[1, 2]
Why is this happening?