# 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:** 15

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [November 9, 2020, 5:47pm UTC](https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696/15 "2020-11-09T17:47:59Z")

</div>

The most general method for iterators that should be O(1) is

```julia
first(Iterators.reverse(iterator))

```

which works for any iterator type that has [implemented reverse iteration](https://docs.julialang.org/en/v1/manual/interfaces/#man-interface-iteration).

However, currently `eachline` has no implementation of reverse-order iteration, so this throws a `MethodError`. In principle, it would be straightforward to implement reverse-order `eachline` for _files_, but it doesn’t seem possible to do efficiently for pipes.

(There is an [`Iterators.last(iterator, n)` iterator](https://github.com/JuliaLang/julia/pull/34868) that uses this `reverse` approach.)

---

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