Fast iterating over first n items of an iterable (not a list) in python
- by martinthenext
Hello!
I'm looking for a pythonic way of iterating over first n items of an iterable (upd: not a list in a common case, as for lists things are trivial), and it's quite important to do this as fast as possible. This is how I do it now:
count = 0
for item in iterable:
do_something(item)
count += 1
if count >= n: break
Doesn't seem neat to me. Another way of doing this is:
for item in itertools.islice(iterable, n):
do_something(item)
This looks good, the question is it fast enough to use with some generator(s)? For example:
pair_generator = lambda iterable: itertools.izip(*[iter(iterable)]*2)
for item in itertools.islice(pair_generator(iterable), n):
so_something(item)
Will it run fast enough as compared to the first method? Is there some easier way to do it?