Negative step indexing on List in Python

243 Views Asked by At

So, my confusion on slicing a list in reverse order took a hit when I tried to compare the two commands, one with their default values and the other one with the actual command

PS: I'm trying to reverse a list using slicing

List = ["Apple", "Grapes", "Mango", "Papaya"]

# Reversing
print(List[::-1])

Here, I get the desired output by skipping both start and end arguments which are optional.

But when I include their default values which are start=0 and end=len(List), I get an empty list

print(List[0:3:-1])

Empty list output

Why so?

1

There are 1 best solutions below

1
On

I think the range should be indicated in reverse order: print(List[3:0:-1]) - although I don't get 'Apples' if I do this.

Why not use reversed(List) instead?