I have an array over which I have to iterate forwards and backwards, depending on circumstances.

Is there a better way than just to use
`var array = ["A", "B", "C", "D"]`
`var array_backwards = ["D", "C", "B", "A"]`
and use each array accordingly? My first instinct was to use the `invert()` function, but I saw that this does not return the array inverted, but inverts it in place. I guess I could probably use `array.duplicate().invert()` instead of declaring it by hand, but this also seems a bit clunky to me.

in Engine

You can do this by using an index and inverting the step:

``````for i in range(10, 0, -1):
print(i)
``````

But that prints:

``````10
9
8
7
6
5
4
3
2
1
``````

So either `range(9, -1, -1)` or use `i-1`?

+1 vote

`var array = ["A", "B", "C", "D"]`
`var arrayinv = []`
`func _ready():`
`arrayinv = array.duplicate()`
`arrayinv.invert()`
`print(arrayinv)`
`pass`
Works great but you could also use:
`var array = ["A", "B", "C", "D"]`
`var arrayinv =[]`
`func _ready():`
`for i in array:`
`arrayinv.push_front(i)`
`print(arrayinv)`
`pass`

hope i could help :)

by (32 points)

It's and old post but this is another possible solution:

``````for x in array.size():
var value = array[-x-1]
``````

Negative index goes backwards.

by (397 points)
edited by
``````var x = [1, 2, 3, 4, 5]

for i in range(x.size()-1, -1, -1):
var element = x[i]
print(element)
# output = 5, 4, 3, 2, 1
``````