Search code examples
pythoniterator

Cleanest way to get last item from Python iterator


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]

Solution

  • item = defaultvalue
    for item in my_iter:
        pass