2

How do I get the last element of an iterator? I'm aware that I have to exhaust the iterator and return the last value it produced, so the plain approach would be:

def last(it):
    for value in it:
        pass
    return value

(You might want to catch the NameError and raise something else for empty input, but you get the idea.)

Is there a simpler solution I didn't think of, e. g. using itertools.islice() (it doesn't seem to accept negative indexes, though) or something similar?

Alfe
  • 56,346
  • 20
  • 107
  • 159
  • you can refer [here](https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator) – Shijith Jun 04 '19 at 12:02

4 Answers4

5

A simpler solution could be to use Extended Iterable Unpacking:

*_, last = it

Example:

it = range(10)
*_, last = it
print(last)
# 9
yatu
  • 86,083
  • 12
  • 84
  • 139
  • are you sure `range()` returns an iterator and not a list? – Gsk Jun 04 '19 at 12:03
  • @Gsk `isinstance(range(10), list)` – yatu Jun 04 '19 at 12:03
  • 1
    Unfortunately it comes close to `list(it)[-1]` which keeps all elements in memory at once as well (your solution stores them briefly in `_`). – Alfe Jun 04 '19 at 12:07
  • @yatu sorry, wrong wording of the question: [`range()` returns an iterable, not an iterator](https://stackoverflow.com/questions/21803830/why-is-the-range-object-not-an-iterator). I'm just curious, I find your answer interesting – Gsk Jun 04 '19 at 12:10
2

Maybe you can use

list(it)[-1]

where it is the iterator.

You convert it into a list and get the last element.

J...S
  • 5,079
  • 1
  • 20
  • 35
1

This is not a pythonic way but just some other solution. If you are ok to use toolz. Then you can do the following.

from toolz import last

last(it)
Praveenkumar
  • 2,056
  • 1
  • 9
  • 18
1

The following is about 26% faster than

def last(it):
    for value in it:
        pass
    return value

as it does the iteration outside of the interpreter:

import collections
def last(iterator):
    return collections.deque(iterator, maxlen=1).pop()

This raises IndexError if the deque is empty otherwise it returns the last value.

The idea for this comes from the consume example in the itertools module.

Dan D.
  • 73,243
  • 15
  • 104
  • 123