Cleanest way to get last item from Python iterator
Solution 1:
item = defaultvalue
for item in my_iter:
pass
Solution 2:
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()
Solution 3:
Use a deque
of size 1.
from collections import deque
#aa is an interator
aa = iter('apple')
dd = deque(aa, maxlen=1)
last_element = dd.pop()