# Why no \`last(::Generator)\`?

**URL:** https://discourse.julialang.org/t/why-no-last-generator/65429
**Category:** Internals & Design
**Created:** [July 28, 2021, 11:37am UTC](https://discourse.julialang.org/t/why-no-last-generator/65429 "2021-07-28T11:37:17Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![jlbosse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlbosse/32/11274_2.png) [@jlbosse](https://discourse.julialang.org/u/jlbosse)
#### Post date: [July 28, 2021, 11:37am UTC](https://discourse.julialang.org/t/why-no-last-generator/65429/1 "2021-07-28T11:37:17Z")

</div>

Is there a good reason, why `last` is not implemented for `Generators`?

I came up with

```julia
function Base.last(iter::Base.Generator)
    x = last(iter.iter)
   return iter.f(i)
end

```

which does exactly what I would expect (and also in O(1) time, like the default implementation of `last(a) = a[end]`.

If this has simply been overlooked in the past, should I open a PR?

**Quick example**  
Without my implementation the current situation is

```julia
julia> iter = (i^2 for i in 1:10)
julia> last(iter)
ERROR: MethodError: no method matching lastindex(::Base.Generator{UnitRange{Int64}, var"#1#2"})
Closest candidates are:
  lastindex(::Any, ::Any) at abstractarray.jl:348
  lastindex(::Core.SimpleVector) at essentials.jl:598
  lastindex(::Tuple) at tuple.jl:26

```

and after defining it we get

```julia

julia> iter = (i^2 for i in 1:10)
julia> last(iter)
100

```

as desired.

---

<div class="post-metadata">

### Author: ![tbeason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tbeason/32/15898_2.png) [@tbeason](https://discourse.julialang.org/u/tbeason)
#### Post date: [July 28, 2021, 12:17pm UTC](https://discourse.julialang.org/t/why-no-last-generator/65429/2 "2021-07-28T12:17:08Z")

</div>

I believe that is because general iterators are not required to have finite length.

---

<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: [July 28, 2021, 12:23pm UTC](https://discourse.julialang.org/t/why-no-last-generator/65429/3 "2021-07-28T12:23:55Z")

</div>

See [Getting the last element of an iterator](https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696/) for a previous discussion.

See also [https://github.com/JuliaLang/julia/pull/37648](https://github.com/JuliaLang/julia/pull/37648)

---

<div class="post-metadata">

### Author: ![jlbosse](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlbosse/32/11274_2.png) [@jlbosse](https://discourse.julialang.org/u/jlbosse)
#### Post date: [July 28, 2021, 1:14pm UTC](https://discourse.julialang.org/t/why-no-last-generator/65429/4 "2021-07-28T13:14:32Z")

</div>

The discussion in the PR answers my question. Thanks!
