Why is the list [:: - 1] not equal to the list [: len (list): - 1]?

When slicing in python, omitting the portion of the end slice (that is, the end in list[:end:] ), the end result is defined as "the size of the chopped string." *

However, this is not like using the step argument (step in list[::step] ) in the slice, at least when the argument step is -1 . A simple example:

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

This means that in the case of the step argument passed, the value of the skipped end is not equivalent to the explicitly passed size of the sliced ​​object.

This may just be a failure of my reading the documentation, but I would like to understand why my previous example seems to contradict the Python documentation about excluding end values ​​in slices and, ideally, where this document is documented.


* Fragment indices have useful defaults; the omitted first index is zero by default; the omitted second index defaults to the size of the sliced ​​row.
+7
python slice
source share
2 answers

The documentation you refer to is a tutorial that provides only an unofficial overview of Python syntax and semantics. He does not explain all the details. You will notice that the textbook page you contacted does not even discuss negative indexes.

The actual documentation is provided in the reference library under the sequence types section. Although it is a bit concise and not easy to understand on first reading, it explains that for the fragment [i:j:k] :

If I or j are omitted or None, they become "final" values ​​(the end of which depends on the sign of k).

+6
source share

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

+2
source share

All Articles