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

Time:09-02

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]

CodePudding user response:

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.

CodePudding user response:

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]
  • Related