Cleanest way to get last item from Python iterator

Question:

What’s the best way of getting the last item from an iterator in Python 2.6? For example, say

my_iter = iter(range(5))

What is the shortest-code / cleanest way of getting 4 from my_iter?

I could do this, but it doesn’t seem very efficient:

[x for x in my_iter][-1]
Asked By: Peter

||

Answers:

item = defaultvalue
for item in my_iter:
    pass
Answered By: Thomas Wouters

I would use reversed, except that it only takes sequences instead of iterators, which seems rather arbitrary.

Any way you do it, you’ll have to run through the entire iterator. At maximum efficiency, if you don’t need the iterator ever again, you could just trash all the values:

for last in my_iter:
    pass
# last is now the last item

I think this is a sub-optimal solution, though.

Answered By: Chris Lutz

There’s this

list( the_iter )[-1]

If the length of the iteration is truly epic — so long that materializing the list will exhaust memory — then you really need to rethink the design.

Answered By: S.Lott

This is unlikely to be faster than the empty for loop due to the lambda, but maybe it will give someone else an idea

reduce(lambda x,y:y,my_iter)

If the iter is empty, a TypeError is raised

Answered By: John La Rooy

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
Answered By: John La Rooy

The question is wrong and can only lead to an answer that is complicated and inefficient.
To get an iterator, you of course start out from something that is iterable, which will in most cases offer a more direct way of accessing the last element.

Once you create an iterator from an iterable you are stuck in going through the elements, because that is the only thing an iterable provides.

So, the most efficient and clear way is not to create the iterator in the first place but to use the native access methods of the iterable.

Answered By: ludwig

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)
Answered By: martin23487234

See this code for something similar:

http://excamera.com/sphinx/article-islast.html

you might use it to pick up the last item with:

[(last, e) for (last, e) in islast(the_iter) if last]
Answered By: James Bowman

As simple as:

max(enumerate(the_iter))[1]
Answered By: Chema Cortes

I would just use next(reversed(myiter))

Answered By: thomas.mac

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()
Answered By: Dhia

The toolz library provides a nice solution:

from toolz.itertoolz import last
last(values)

But adding a non-core dependency might not be worth it for using it only in this case.

Answered By: lumbric

The question is about getting the last element of an iterator, but if your iterator is created by applying conditions to a sequence, then reversed can be used to find the “first” of a reversed sequence, only looking at the needed elements, by applying reverse to the sequence itself.

A contrived example,

>>> seq = list(range(10))
>>> last_even = next(_ for _ in reversed(seq) if _ % 2 == 0)
>>> last_even
8
Answered By: Wyrmwood

You could use the great more_itertools library and the last(iterable[, default]) function:

more_itertools.last(iterable[, default]) [source]

Return the last item of iterable, or default if iterable is empty.

>>> last([0, 1, 2, 3])
3
>>> last([], 'some default')
'some default'

If default is not provided and there are no items in the iterable, raise ValueError.

It combines the deque approach proposed by some of the answers here, with some additional improvements (see the source for details).

Answered By: Czechnology