Home > Net >  Understanding output of slicing operation
Understanding output of slicing operation

Time:09-22

I have a list object which looks as below:

lst = [50,34,98,8,10]

The output for the statement print(lst[:5:-2]) is coming as blank []

My understanding is that print(lst[:5:-2]) translates to print(lst[-1:5:-2])

This means:

  • start from index -1 # this corresponds to value 10
  • stop at index 4 # this corresponds to value 10
  • perform increment of -2

As start and stop are pointing to 10 so I am expecting the output to be 10 here.

CodePudding user response:

An easy way to understand python slicing syntax is to think about it as such: slice[start:stop:step].

What this means is that your starting point is start, here that's index -1 since the starting position for a negative step is -1. It stops at stop, here that's the 4th element. When using a step of -2 the first iteration will be the 4th element. Thus nothing is returned since you've already arrived at your stop condition.

CodePudding user response:

So the documentation is here, and additional explanation here. And another additional explanation you can read here. On your case that syntax is same as

print(lst[-1:5:-2])

OR

print(lst[-1:-1:-2])
  • Note this is because python also can use negative indexing, and last item is indexed as -1... till the first item indexed as -len(list). So index 5 is same as -1
  • Also the negative step indicates that the starting point is the last item of list or index -1

So what it's done:

  • Start from index -1 # this corresponds to value 10
  • Stop at index -1 # this correspond to value 10
  • Using -2 as step

because the step is -2 and the start is already smaller than or same with stop (start <= stop) the slice result to empty because nothing taken from the list.

for example how to use negative step, you can run

print(lst[5:0:-2])

same as

print(lst[-1:-5:-2])

that's will return [10, 98]

print(lst[5::-2])

same as

print(lst[-1:-6:-2])

that's will return [10, 98, 50]

You can still use -len(list)-1 for indexing to inclusive the first item that contains in index -len(list).

  • Related