# Obtaining the last element of a ProductIterator

**URL:** <https://discourse.julialang.org/t/obtaining-the-last-element-of-a-productiterator/54259>\
**Category:** General Usage\
**Tags:** question, iterators\
**Created:** [January 30, 2021, 9:15am UTC](https://discourse.julialang.org/t/obtaining-the-last-element-of-a-productiterator/54259 "2021-01-30T09:15:45Z")\
**Posts on this page:** 1\
**Showing post:** 2

<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:** [January 30, 2021, 11:59am UTC](https://discourse.julialang.org/t/obtaining-the-last-element-of-a-productiterator/54259/2 "2021-01-30T11:59:02Z")

</div>

In a future version (1.6?) the following works:

```julia
julia> it = Iterators.product(1:3, 2:3)
Base.Iterators.ProductIterator{Tuple{UnitRange{Int64}, UnitRange{Int64}}}((1:3, 2:3))

julia> last(it, 1)
1-element Vector{Tuple{Int64, Int64}}:
 (3, 3)

```

This was added in [https://github.com/JuliaLang/julia/pull/34868](https://github.com/JuliaLang/julia/pull/34868)

This works as long as the iterator implements `reverse`. There was recently a discussion here about the difficulties of adding a generic `last` method: [Getting the last element of an iterator](https://discourse.julialang.org/t/getting-the-last-element-of-an-iterator/49696/). I planned to submit a PR but as explained in that thread I couldn’t find an implementation that was performant and backward-compatible.

As a workaround @mschauer suggested `foldl((_, y) -> y, itr)`, which also works fine here:

```julia
julia> foldl((_,y)->y, Iterators.product(1:3, 2:3))
(3, 3)

```

---

_[View the full topic](https://discourse.julialang.org/t/obtaining-the-last-element-of-a-productiterator/54259)._
