There is a fantastic package in Python called itertools
.
But before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the __iter__()
class method that provides an iterator type. "Understanding Python's 'for' statement" is a nice article covering how the for-in
statement actually works in Python and provides a nice overview on how the iterator types 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 do special sequencing, this is the first place to look into.
At the bottom you can find the Recipes section that contain recipes for creating an extended toolset using the existing itertools as building blocks.
And there's 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(islice(iterator, n), maxlen=0)
Here's a quick, readable, example on 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):
# Disregard 6, 7, 8, 9 (5 doesn't get printed just as well)
consume(iterator, 4)
else:
print number
1
2
3
4
10
11
12
13
14
15