Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explain the reverse of a sequence by slice notation a[::-1]

From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello" >>> print(a[::-1]) olleh 

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1])) 0 

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

like image 212
Alex Avatar asked Jun 06 '17 09:06

Alex


People also ask

How do you reverse the order of sequence for slicing?

Using a[::-1] in Python to Reverse an Object Like an Array or String. As we saw above, we have a[start: stop: step] step in slicing, and -1 means the last element of the array. Therefore, a[::-1] starts from the end till the beginning reversing the given sequence that was stored.

How do you slice a sequence?

In order to slice a sequence, we need to use a colon within square brackets. In other words, the colon (:) in subscript notation [square brackets] make slice notation.

How do you reverse in slicing in Python?

Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0. The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

What is :: In slicing?

Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:) With this operator, one can specify where to start the slicing, where to end, and specify the step.


1 Answers

I think the docs are perhaps a little misleading on this, but the optional arguments of slicing if omitted are the same as using None:

>>> a = "hello" >>> a[::-1] 'olleh' >>> a[None:None:-1] 'olleh' 

You can see that these 2 above slices are identical from the CPython bytecode:

>>> import dis >>> dis.dis('a[::-1]') # or dis.dis('a[None:None:-1]')   1           0 LOAD_NAME                0 (a)               3 LOAD_CONST               0 (None)               6 LOAD_CONST               0 (None)               9 LOAD_CONST               2 (-1)              12 BUILD_SLICE              3              15 BINARY_SUBSCR              16 RETURN_VALUE 

For a negative step, the substituted values for None are len(a) - 1 for the start and -len(a) - 1 for the end:

>>> a[len(a)-1:-len(a)-1:-1] 'olleh' >>> a[4:-6:-1] 'olleh' >>> a[-1:-6:-1] 'olleh' 

This may help you visualize it:

    h  e  l  l  o        0  1  2  3  4  5 -6 -5 -4 -3 -2 -1 
like image 189
Chris_Rands Avatar answered Oct 07 '22 17:10

Chris_Rands