The `[]` operator more than syntactic sugar?

Question:

The most common syntax of slice objects seems to be int:int:int, and specifically within the [] operator of tuples lists and strs. It makes sense why this syntax can’t be used to instantiate a slice,

Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 0:-1:1
  File "<stdin>", line 1
    0:-1:1
    ^
SyntaxError: illegal target for annotation

but when testing to see where the slice object is implicitly handled, it turns out to be in the [] operator:

>>> [].__getitem__(0:-1:1)
  File "<stdin>", line 1
    [].__getitem__(0:-1:1)
                    ^
SyntaxError: invalid syntax
>>> [][0:-1:1]
[]
>>> "".__getitem__(0:-1:1)
  File "<stdin>", line 1
    "".__getitem__(0:-1:1)
                    ^
SyntaxError: invalid synta
>>> ""[0:-1:1]
''

This seems to conflict with the common interpretation that [] is syntactic sugar. What is going on under the hood of []?

Asked By: thebadgateway

||

Answers:

The [] operator creates a slice object and passes that to __getitem__:

>>> [1, 2, 3][0:-1:1]
[1, 2]
>>> [1, 2, 3].__getitem__(slice(0, -1, 1))
[1, 2]
Answered By: Samwise
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.