Fast iterating over first n items of an iterable (not a list) in python

Posted by martinthenext on Stack Overflow See other posts from Stack Overflow or by martinthenext
Published on 2010-04-23T21:47:09Z Indexed on 2010/04/23 22:03 UTC
Read the original article Hit count: 279

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about pythonic