If I'm looping through Python's iterator, how can I find out if now is the last element? I'm looking for some standard library way of doing this, maybe some function in itertools
, is there such? Or some other very short and Pythonic way of doing this.
Of cause I can implement my own helper generator achieving this task:
def is_last(it):
first = True
for e in it:
if not first:
yield False, prev
else:
first = False
prev = e
if not first:
yield True, prev
for last, e in is_last(range(4)):
print(last, e)
Which outputs:
False 0
False 1
False 2
True 3
Also if I'm looping through simple range I can always compare to upper limit (below is solution for positive step
):
start, stop, step = 10, 21, 3
for i in range(start, stop, step):
last = i + step >= stop
print(last, i)
Which outputs:
False 10
False 13
False 16
True 19
This above is also obvious and probably easiest solution for the case of simple range, unfortunatelly it needs keeping stop/step in separate variables. But anyway range-case is not very interesting. What about the case of any arbitrary iterator, is there a Pythonic way to solve this case?