# Getting the last element of an iterator

**URL:** <https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696>\
**Category:** General Usage\
**Tags:** question\
**Created:** [November 6, 2020, 6:02pm UTC](https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696 "2020-11-06T18:02:17Z")\
**Posts on this page:** 1\
**Showing post:** 30

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [November 10, 2020, 2:11pm UTC](https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696/30 "2020-11-10T14:11:42Z")

</div>

I also don’t understand this focus on the complexity guarantee… It seems very peculiar to `last`, and generally doesn’t feel Julian to forbid implementation of generally useful methods like this.

@Henrique_Becker please consider the possibility that the documentation was poorly worded and misunderstood. Maybe as @apo383 suggests it was never the intention to forbid `last` in the O(n) case.

That would also explain the inconsistency with `lastindex` which says nothing about O(1). Consider again the `LinkedList` case. It’s not even necessary to inherit `AbstractArray`:

```julia
import Base: getindex, lastindex
struct LinkedList end
getindex(::LinkedList, ::Int) = ...
lastindex(::LinkedList) = ...

```

Reasonable code, no inheritance, and it gives a “slow” `last`.

Also look at this excerpt from [HISTORY.md](https://github.com/JuliaLang/julia/blob/master/HISTORY.md):

> New function `ncodeunits(s::AbstractString)` gives the number of code units in a string. The generic definition is constant time but calls `lastindex(s)` which may be inefficient.

This all suggests that this weird constraint in the documentation of `last` was never meant as a constraint.

---

_[View the full topic](https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696)._
