Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does list[::-1] not equal list[:len(list):-1]?

Tags:

python

slice

When slicing in python, omitting the end portion of the slice (ie the end in list[:end:]) results in end being defined as "the size of the string being sliced." *

However, this doesn't seem to hold true when using the step argument (the step in list[::step]) in a slice, at least when the step argument is -1. A simple example:

>>> l = [1, 2, 3]
>>> l[::-1]
[3, 2, 1]
>>> l[:len(l):-1]
[]

This indicates that in the case of a step argument being passed, an omitted end value is not equivalent to explicitly passing the size of the object being sliced.

Perhaps this is just a failure of mine reading the documentation, but I'd like to understand why my above example seems to contradict the Python documentation about omitting end values in slices, and ideally where this different is documented.


* 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.
like image 384
Nolen Royalty Avatar asked Apr 28 '16 00:04

Nolen Royalty


Video Answer


2 Answers

The documentation you're referencing is the tutorial, which gives only an informal overview of Python syntax and semantics. It doesn't explain all the details. You'll note that the tutorial page you linked to doesn't even discuss negative indices.

The actual documentation is given in the library reference under sequence types. Although it is a bit terse and not easy to understand on a first read, it does clarify that for a slice [i:j:k]:

If i or j are omitted or None, they become “end” values (which end depends on the sign of k).

like image 55
BrenBarn Avatar answered Oct 01 '22 01:10

BrenBarn


l[::-1] is the same thing as l.__getitem__(slice(None, None, -1)). Since the start and the stop are both None, the list will be traversed from one end to the other. The step argument determines the direction as well as the step.

like image 30
zondo Avatar answered Oct 01 '22 00:10

zondo