item = defaultvalue
for item in my_iter:
pass
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()
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()
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
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