Fast iterating over first n items of an iterable 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
21:53 UTC
Read the original article
Hit count: 363
Hello!
I'm looking for a pythonic way of iterating over first n
items of a list, 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_somethin(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