I need to generate numpy arrays getting elements in reverse order from another array.
Toy example code
Lets say I use following toy example code:
import numpy as np
a = np.array([1,2,3,5,8,13])
n = len(a)
for i in range(n):
print a[n:n-i-2:-1]
I would expect that last print is a [13 8 5 3 2 1]
, however I get an empty array []
as seen below:
>>>
[13]
[13 8]
[13 8 5]
[13 8 5 3]
[13 8 5 3 2]
[]
Fix
So I had to create below fix to my code within the for
loop to get what I expect.
for i in range(n):
print a[n-i-1:n+1][::-1]
Which means selecting the arrays from the original array and then reversing it.
Questions
- Why when I try
a[6:0:-1]
I get[13, 8, 5, 3, 2]
but once I trya[6:-1:-1]
I get an emtpy array[]
? I would expect to get the whole array reversed as when you trya[::-1]
. - Is the fix I implemented the way to go or there is something I'm missing here?
Edit
The post Understanding slice notation answers my first question but not the second one.