Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice operator with end index 0 [duplicate]

a='0123456789'

>>> a
'0123456789' 

>>> a[1:-6:1] # working as expected
'123'

>>> a[2:-1:-1] # i was expecting '210' as answer based on start index=2 end index=0
''

Please help in understanding how the second slice operator returned nothing

like image 796
sai dattu Avatar asked Aug 21 '18 05:08

sai dattu


Video Answer


2 Answers

Negative indices for start and stop are always converted by implicitly subtracting from len(sequence). So a[2:-1:-1] translates to a[2:len(a)-1:-1], or a[2:9:-1], which reads in English as "start at index 2, and go backwards by one until you're at or below index 9".

Since you start at index 2, you're already at or below 9, and the slice ends immediately.

If you want to slice from index to back to the beginning of the string, either omit the end index (which for negative slice means continue until "beginning of string"):

a[2::-1]

or provide it explicitly as None, which is what omitting stop ends up using implicitly:

a[2:None:-1]
like image 71
ShadowRanger Avatar answered Oct 05 '22 20:10

ShadowRanger


I think, you want to do something like this:

a[2::-1]  # produces: [2, 1, 0]

Slicing from 2 to -1 with step -1 (what you did) does yield an empty list because you want to move forward with negative step size and hence you receive an empty list.

This SO post provides the explanation:

It's pretty simple really:

a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:end:step] # start through not past end, by step

The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).

The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

like image 28
tahesse Avatar answered Oct 05 '22 19:10

tahesse