I am going through a generator, whats the Pythonic way of determining if the current element is the first or last element of a generator, given that they need special care?
thanks
basically generating tags, so i have items like
<div class="first">1</div>
<div>...</div>
<div class="last">n</div>
so i would like to keep the last item in loop?
Here's an enumerate-like generator that skips ahead one; it returns -1 for the last element.
>>> def annotate(gen):
... prev_i, prev_val = 0, gen.next()
... for i, val in enumerate(gen, start=1):
... yield prev_i, prev_val
... prev_i, prev_val = i, val
... yield '-1', prev_val
>>> for i, val in annotate(iter(range(4))):
... print i, val
...
0 0
1 1
2 2
-1 3
It can't tell whether the generator passed to it is "fresh" or not, but it still tells you when the end is nigh:
>>> used_iter = iter(range(5))
>>> used_iter.next()
0
>>> for i, val in annotate(used_iter):
... print i, val
...
0 1
1 2
2 3
-1 4
Once an iterator is used up, it raises StopIteration
as usual.
>>> annotate(used_iter).next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in annotate
StopIteration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With