How to Explain the Reverse of a Sequence by Slice Notation A[::-1]

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

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

Why does reversing a list using slice notation with 0 as stop not return the entire list?

Slice notation in short:

[ <first element to include> : <first element to exclude> : <step> ]

If you want to include the first element when reversing a list, leave the middle element empty, like this:

foo[::-1]

You can also find some good information about Python slices in general here:

Explain Python's slice notation

reversing list using slicing [ : 0:-1] in Python

 >>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> L[1:3]
[1, 2]

index 3 is excluding

>>> L[0:10:1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

index 10 is excluding, and if you want to select all,you should use:

>>>L[0:11:1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

but you can not get L[11],it will be throw IndexError,because you only have 11 elements,the max index is 10, the reason L[0:11:1] will not out of bound because this slice will not access to L[11] only from index 0 to 10.

>>> L[10:0:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

-1 is a step of slice reversely,also 0 is excluding,

and L[10:-1:-1] is equivalent to L[10:10:-1] ,because the first -1 means the last index of L

>>> L[10:-12:-1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

index -11 is equivalent to index 0, index -12 is equivalent to index before 0

Understanding slicing

The syntax is:

a[start:stop]  # items start through stop-1
a[start:] # items start through the rest of the array
a[:stop] # items from the beginning through stop-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:stop:step] # start through not past stop, by step

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

The other feature is that start or stop 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.

Relationship with the slice object

A slice object can represent a slicing operation, i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similarly to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported.
To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

How to explain the first colon in Python slice syntax list[::-1]

The colons with no values given means resort to default values. The default values for the start index when the step is negative is len(l), and the end index is -len(l)-1. So, the reverse slicing can be written as

l[len(l):-len(l)-1:-1]

which is of the form.

l[start:end:step]

Removing the default values, we can use it in a shorter notation as l[::-1].

It might be useful to go through this question on Python's Slice Notation.

Understanding string reversal via slicing

Sure, the [::] is the extended slice operator. It allows you to take substrings. Basically, it works by specifying which elements you want as [begin:end:step], and it works for all sequences. Two neat things about it:

  • You can omit one or more of the elements and it does "the right thing"
  • Negative numbers for begin, end, and step have meaning

For begin and end, if you give a negative number, it means to count from the end of the sequence. For instance, if I have a list:

l = [1,2,3]

Then l[-1] is 3, l[-2] is 2, and l[-3] is 1.

For the step argument, a negative number means to work backwards through the sequence. So for a list::

l = [1,2,3,4,5,6,7,8,9,10]

You could write l[::-1] which basically means to use a step size of -1 while reading through the list. Python will "do the right thing" when filling in the start and stop so it iterates through the list backwards and gives you [10,9,8,7,6,5,4,3,2,1].

I've given the examples with lists, but strings are just another sequence and work the same way. So a[::-1] means to build a string by joining the characters you get by walking backwards through the string.

Please explain Python sequence reversal

The slice notation goes like this:

my_list[start:end:step]

So, when you do [::-1], it means:

  • start: nothing (default)
  • end: nothing (default)
  • step: -1 (descendent order)

So, you're going from the end of the list (default) to the first element (default), decreasing the index by one (-1).

So, as many answers said, there is no sorting nor in-place swapping, just slice notation.



Related Topics



Leave a reply



Submit