Question

I read that everything is an object in Python. So what is 2:4 in L[2:4]? Is it a slicing object? When I just type 2:4 in the interpreter, an SyntaxError is raised.

Was it helpful?

Solution

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.

OTHER TIPS

Python allows slicing of lists and strings. You need to create an object for L for this syntax to work. Try these as examples:

>>> L = [0,1,2,3,4,5,6]
>>> L[2:4]

>>> L = "This is a test"
>>> L[2:4]
>>> L[2:]
>>> L[:4]
>>> L[-3:]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top