Dila
Dila

Reputation: 689

Julia: Iterating in reverse

Let's say I have the following list:

a = [1, 2, 3, 4, 5]

Instead of stepping through the list from 1 to 5

for i in 1:length(a)

I would like to step through it from 5 to 1. Is there a convenient way to do this in Julia?

Upvotes: 4

Views: 722

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69949

There are many options.

Do you want to iterate a in reverse or indices into a?

First assume you wan to iterate a, then Iterators.reverse(a) is an efficient way to do it.

If you want to iterate indices of a then an efficient option is reverse(eachindex(a)). You could also write Iterators.reverse(eachindex(a)) but this time it is enough to use standard reverse function (I have not recommended it for reversing a as it would allocate a new vector).

Note that in your case it would be also correct to write length(a):-1:1, but this is not a recommended pattern in general, as you cannot be sure what pattern of indexing your a object supports (in your case it is a vector using 1-based indexing, but it could be an object that uses a different indexing style).

Upvotes: 5

Related Questions