Search code examples
pythonarraysnumpyreverse

Get some elements from numpy array in reverse order


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

  1. Why when I try a[6:0:-1] I get [13, 8, 5, 3, 2] but once I try a[6:-1:-1] I get an emtpy array []? I would expect to get the whole array reversed as when you try a[::-1].
  2. 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.


Solution

  • Here is a slightly more elegant fix.

    for i in range(n):
        print(a[n:-i-2:-1])
    

    or even more elegant

    for i in range(n):
        print(a[:-i-2:-1])
    

    both print

    [13]
    [13  8]
    [13  8  5]
    [13  8  5  3]
    [13  8  5  3  2]
    [13  8  5  3  2  1]
    

    It also demonstrates the rule that negative indices count from the top, which is why your original loop switches behavior when the stop index gets to -1.