views:

171

answers:

2

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)?

+6  A: 

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.

Unknown
..although you can do some nifty tricks with `itertools`.
John Fouhy
Thanks.This is what I wanted.
Goutham
The "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.
Alex Martelli
+5  A: 

The itertools.dropwhile() function might be helpful, too:

dropwhile(lambda x: x<5, xrange(10))
unbeknown
+1 beautiful answer
ThomasH