Python has a fantastic package called itertools .
But before I get it, this will serve as a good explanation of how the iterative protocol is implemented in Python. When you want to provide iteration over your container, you specify the class method __iter__() , which provides the type of iterator . Understanding Python for a statement is a good article that describes how the for-in statement actually works in Python and gives a good overview of how iterators work.
Take a look at the following:
>>> sequence = [1, 2, 3, 4, 5] >>> iterator = sequence.__iter__() >>> iterator.next() 1 >>> iterator.next() 2 >>> for number in iterator: print number 3 4 5
Now back to itertools . The package contains functions for various iteration purposes. If you ever need to complete a special sequence, this is the first place you need to pay attention to.
Below you can find the Recipes section, which contains recipes for creating an advanced toolbox using existing itertools as building blocks.
And there is an interesting function that does exactly what you need:
def consume(iterator, n): '''Advance the iterator n-steps ahead. If n is none, consume entirely.''' collections.deque(itertools.islice(iterator, n), maxlen=0)
Here is a quick, readable example of how it works (Python 2.5):
>>> import itertools, collections >>> def consume(iterator, n): collections.deque(itertools.islice(iterator, n)) >>> iterator = range(1, 16).__iter__() >>> for number in iterator: if (number == 5):
Filip DupanoviΔ Sep 25 '09 at 0:27 2009-09-25 00:27
source share