Why the last element in array using negative index slice is not showing?

Question:

I want to slice an array from the last element to the first element using a for loop to reduce the array, this is my code but for an reason the last element is not showing. Ignore the name of the function.

    def find_even_index(arr):
        for i in range(len(arr)):
            print(arr[-(len(arr)):-i])

    find_even_index([1,2,3,4,3,2,1]),3)

Result:

    []
    [1, 2, 3, 4, 3, 2]
    [1, 2, 3, 4, 3]
    [1, 2, 3, 4]
    [1, 2, 3]
    [1, 2]
    [1]

Expect result:

    [1, 2, 3, 4, 3, 2, 1]
    [1, 2, 3, 4, 3, 2]
    [1, 2, 3, 4, 3]
    [1, 2, 3, 4]
    [1, 2, 3]
    [1, 2]
    [1]
Asked By: juangalicia

||

Answers:

Working:

def find_even_index(arr):
    for i in range(len(arr)):
        print(arr[:len(arr) - i])

find_even_index([1,2,3,4,3,2,1])

#prints:
[1, 2, 3, 4, 3, 2, 1]
[1, 2, 3, 4, 3, 2]
[1, 2, 3, 4, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]

When you had

arr[:-i]

i started at 1, so you told it, in essence, to do

arr[0:-0]
# which is
arr[0:0]

Which is what caused it to print nothing. instead, start at the length of the array and incrementally subtract 1.

Answered By: Mitchnoff

The farthest right you can specify with a negative index is -1, which refers to the final item in a sequence. However, slice semantics are that the index following the : is excluded from the slice.

Therefore, there is no way, using a negative index to the right of the :, to include the final item in a list.

You could "fix" this in your function by replacing -i with -i if i else len(arr):

def find_even_index(arr):
    for i in range(len(arr)):
        print(arr[-(len(arr)):-i if i else len(arr)])

find_even_index([1,2,3,4,3,2,1])

Output:

[1, 2, 3, 4, 3, 2, 1]
[1, 2, 3, 4, 3, 2]
[1, 2, 3, 4, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]
Answered By: constantstranger
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.