Python for loop and iterator behavior

Your suspicion is correct: the iterator has been consumed. In actuality, your iterator is a generator, which is an object which has the ability to be iterated through only once. type((i for i in range(5))) # says it’s type generator def another_generator(): yield 1 # the yield expression makes it a generator, not a function … Read more

split a generator/iterable every n items in python (splitEvery)

from itertools import islice def split_every(n, iterable): i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n)) Some tests: >>> list(split_every(5, range(9))) [[0, 1, 2, 3, 4], [5, 6, 7, 8]] >>> list(split_every(3, (x**2 for x in range(20)))) [[0, 1, 4], [9, 16, 25], [36, 49, 64], [81, 100, 121], … Read more