No, 2:4
is not free-standing independent syntax. The syntax translates :
-separtated expressions into a slice()
object instead, and only works in the context of []
item indexing. slice()
is an internal type, see the internal types documentation.
lst[2:4]
is translated to lst[slice(2, 4, None)]
instead. You can see this when using a custom class with __getitem__
method:
>>> class Demo:
... def __getitem__(self, item):
... return item
...
>>> d = Demo()
>>> d[2]
2
>>> d[2:4]
slice(2, 4, None)
>>> d[2::-2]
slice(2, None, -2)
You can create these objects directly, slice()
is a built-in type:
>>> help(slice)
Help on class slice in module builtins:
class slice(object)
| slice(stop)
| slice(start, stop[, step])
|
| Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
[ ... ]
It is the :
part that triggers the slice()
object; you can even pass in multiple slices, even though no standard-library type supports indexing like that:
>>> d[10:, :-5, ::-1, :]
(slice(10, None, None), slice(None, -5, None), slice(None, None, -1), slice(None, None, None))
The last slice in that tuple is represented by a single :
only.
A related object, the Ellipsis
, is created when you use ...
in your indexing:
>>> d[...]
Ellipsis
No standard-library type uses this either, but the Numpy project relies heavily on this singleton object and the multiple-slice functionality to do fantastic things to structured data.