Standard lib version of something like enumerate() that takes a max count iteration parameter?

Peter Otten __peter__ at web.de
Wed Jun 14 14:34:30 EDT 2017


Malcolm Greene wrote:

> Wondering if there's a standard lib version of something like
> enumerate() that takes a max count value?
> Use case: When you want to enumerate through an iterable, but want to
> limit the number of iterations without introducing if-condition-break
> blocks in code.
> Something like:
> 
> for counter, key in enumerate( some_iterable, max_count=10 ):
>     <loop logic here>

Usually you limit the iterable before passing it to enumerate():

for index, value in enumerate(some_seq[:max_count]):
    ...

When you have to deal with arbitrary iterables there's itertools.islice():

from itertools import islice

for index, value in enumerate(islice(some_iterable, max_count)):
   ...

Of course

for index, value in islice(enumerate(some_iterable), max_count):
   ...

is also possible.





More information about the Python-list mailing list