Say I have an iterator.
After iterating over a few items of the iterator, I will have to get rid of these first few items and return an iterator(preferably the same) with the rest of the items. How do I go about?
Also, Do iterators support remove or pop operations (like lists)?
2 Answers
Yes, just use iter.next()
Example
iter = xrange(3).__iter__()
iter.next() # this pops 0
for i in iter:
print i
1
2
You can pop off the front of an iterator with .next(). You cannot do any other fancy operations.
-
9The "official", recommended way, in Python 2.6 and later, is next(iter), not iter.next() [that continues to work in 2.6, but not in 3.*]. With next(x) you can supply a default value as the second argument to avoid getting a StopIteration exception if the iterator is exhausted. Commented Aug 3, 2009 at 4:28
The itertools.dropwhile()
function might be helpful, too:
dropwhile(lambda x: x<5, xrange(10))