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)?
views:
171answers:
2
+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
2009-08-03 04:12:33
..although you can do some nifty tricks with `itertools`.
John Fouhy
2009-08-03 04:18:49
Thanks.This is what I wanted.
Goutham
2009-08-03 04:19:24
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
2009-08-03 04:28:55
+5
A:
The itertools.dropwhile()
function might be helpful, too:
dropwhile(lambda x: x<5, xrange(10))
unbeknown
2009-08-03 09:25:25