Consume an iterable

Arnaud Delobelle arnodel at googlemail.com
Fri Jan 22 10:24:33 EST 2010


Muhammad Alkarouri <malkarouri at gmail.com> writes:

> In the python help for itertools, the following function is provided:
>
> def consume(iterator, n):
>     "Advance the iterator n-steps ahead. If n is none, consume
> entirely."
>     collections.deque(islice(iterator, n), maxlen=0)
>
> What is the advantage of using a collections.deque against, say, the
> following code?
>
> def consume(iterator, n):
>     for _ in islice(iterator, n): pass
>

I remember suggesting this function (under the name of 'exhaust'!) a
while ago - although I don't think there was an optional parameter for
the number of elements consumed.  I hadn't realised it had been deemed
useful by others!

-- 
Arnaud



More information about the Python-list mailing list