Let's look at this part by part:
len(my_list)
is 4. Thus range(len(my_list)-1, 0)
is the same as range(3, 0)
, which is []
in Python 2. (In Python 3, try list(range(3, 0))
to see the same empty list.)
If you want a declining range, use a negative step (third argument):
range(3, 0, -1)
gives [3, 2, 1]
. It doesn't include 0
, because even for negative steps, the upper bound (second argument) is exclusive, i.e., not part of the result. It seems you've worked around this by initializing the temp
variable with the last array in my_list
already before then loop, and then subtracting 1 from the index when using it to access my_list
contents in the loop.
my_list = [array0, array1, array2, array3]
temp = my_list[-1]
for k in range(len(my_list) - 1, 0, -1):
temp = temp + my_list[k - 1]
return temp
would thus probably work.
However, if you need the indices only to access my_list
, you can get rid of them by directly iterating over the elements of my_list
in the (here reverse) order you want:
my_list = [array0, array1, array2, array3]
temp = empty_array # Not quite sure what this has to be. (Depends on your array type.)
for array in reversed(my_list):
temp = temp + array
return temp
I'm assuming your arrays are concatenated in the loop. If it's instead an actual addition (NumPy vector addition, for example — though I don't see why the order of addition would matter for that, except maybe for precision, if the values in my_list
are sorted), use an appropriate zero-element instead of empty_array
.
You can even get rid of the loop completely. If you want to add your arrays:
my_list = [array0, array1, array2, array3]
return sum(reversed(my_list))
If you want to concatenate them:
from itertools import chain
my_list = [array0, array1, array2, array3]
return list(chain.from_iterable(reversed(my_list)))