# Iterate for previous and current elements

**URL:** https://discourse.julialang.org/t/iterate-for-previous-and-current-elements/10321
**Category:** General Usage
**Tags:** question
**Created:** [April 13, 2018, 9:44am UTC](https://discourse.julialang.org/t/iterate-for-previous-and-current-elements/10321 "2018-04-13T09:44:32Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![yakir12](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yakir12/32/297_2.png) [@yakir12](https://discourse.julialang.org/u/yakir12)
#### Post date: [April 13, 2018, 9:44am UTC](https://discourse.julialang.org/t/iterate-for-previous-and-current-elements/10321/1 "2018-04-13T09:44:32Z")

</div>

I’m getting greedy here, but you might have a better way to do this.

Say I want to go through some collection (e.g. `a = 1:5`) but retrieve the current element _and_ the previous one as well. There are two ways I can think of to deal with this:

1. 

```julia
for i in 2:length(a)
    println(a[i - 1], " and ", a[i])
end

```

2. 

```julia
old = shift!(a)
for new in a
    println(old, " and ", new)
    old = new
end

```

What with all the indexing magic going around, I was wondering if there’s a better way…?

Thanks!

---

<div class="post-metadata">

### Author: ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)
#### Post date: [April 13, 2018, 11:05am UTC](https://discourse.julialang.org/t/iterate-for-previous-and-current-elements/10321/2 "2018-04-13T11:05:11Z")

</div>

```julia
julia> using IterTools

julia> for (prev, this) in partition(1:5, 2, 1)
       println(prev, " and ", this)
       end
1 and 2
2 and 3
3 and 4
4 and 5

```
