Iterate for previous and current elements

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. for i in 2:length(a)
        println(a[i - 1], " and ", a[i])
    end
    
  2. 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!

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
8 Likes