Cleanest way to get last item from Python iterator
If you are using Python 3.x:
*_, last = iterator # for a better understanding check PEP 448
print(last)
if you are using python 2.7:
last = next(iterator)
for last in iterator:
continue
print last
Side Note:
Usually, the solution presented above is what you need for regular cases, but if you are dealing with a big amount of data, it's more efficient to use a deque
of size 1. (source)
from collections import deque
#aa is an interator
aa = iter('apple')
dd = deque(aa, maxlen=1)
last_element = dd.pop()
Probably worth using __reversed__
if it is available
if hasattr(my_iter,'__reversed__'):
last = next(reversed(my_iter))
else:
for last in my_iter:
pass
Use a deque
of size 1.
from collections import deque
# aa is an iterator
aa = iter('apple')
dd = deque(aa, maxlen=1)
last_element = dd.pop()
Short version:
last_element, = deque(aa, 1)
item = defaultvalue
for item in my_iter:
pass