This avoids trimming problems: it does not change the order of operations and does not create a new list, which may be important for large lists if you filter the list comprehension.
def first(it, count):
it = iter(it)
for i in xrange(0, count):
yield next(it)
raise StopIteration
print [i for i in first(range(1000), 5)]
It also works correctly with generator expressions, where slicing crashes due to memory usage:
exp = (i for i in first(xrange(1000000000), 10000000))
for i in exp:
print i
source
share