turtle turtle - 1 year ago 69
Python Question

Difficulty with itertools.dropwhile

I'm trying to use

to only return elements from a generator that come after the third element, but I'm having a bit of trouble:

from itertools import dropwhile

it = (i for i in range(10,20))
a = dropwhile(enumerate < 3, it)
TypeError: 'bool' object is not callable

The output I'm looking for is:

[14, 15, 16, 17, 18, 19]

Can anyone explain what is wrong with my code and provide a working solution? Thanks.

Answer Source

itertools provides a function that does exactly what you want and more. From the Python Standard Library,

itertools.islice(iterable[, start], stop[, step])

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position.

>>> import itertools
>>> it = (i for i in range(10, 20)) # it = xrange(10, 20)
>>> a = itertools.islice(it, 4, None)
>>> list(a)
[14, 15, 16, 17, 18, 19]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download