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

<div class="post-metadata">

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

</div>

> [@Length from iterator?](https://discourse.julialang.org/t/length-from-iterator/27821/20):
>
> Sometimes I found it useful to get the length and the last iterate, e.g. if the iterator does some numerical work until a convergence criteria holds. So a generally useful function is: lastiterate(itr) = foldl((x, y) -\> y, itr) And then julia\> lastiterate('A':'Z') 'Z' and julia\> lastiterate(enumerate('A':'Z')) (26, 'Z')

```julia
lastiterate(itr) = foldl((_, y) -> y, itr)

```

or

```julia
lastiterate(itr) = applicable(last, itr) ? last(itr) : foldl((_, y) -> y, itr)

```

---

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