Cleanest way to get last item from Python iterator

Peter picture Peter · Jan 26, 2010 · Viewed 52.9k times · Source

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]

Answer

Thomas Wouters picture Thomas Wouters · Jan 26, 2010
item = defaultvalue
for item in my_iter:
    pass