Cleanest way to get last item from Python iterator Cleanest way to get last item from Python iterator python-3.x python-3.x

Cleanest way to get last item from Python iterator


item = defaultvaluefor item in my_iter:    pass


If you are using Python 3.x:

*_, last = iterator # for a better understanding check PEP 448print(last)

if you are using python 2.7:

last = next(iterator)for last in iterator:    continueprint 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 interatoraa = iter('apple')dd = deque(aa, maxlen=1)last_element = dd.pop()


Use a deque of size 1.

from collections import deque#aa is an interatoraa = iter('apple')dd = deque(aa, maxlen=1)last_element = dd.pop()