giorgi shengelaia giorgi shengelaia - 27 days ago 25
Python Question

How can I use colon (:) in variable

I want to write code like this:

index = 0:2
print(list[index])


but this does not work.

Is there any way I can store all parts of the
[...:...]
syntax in a variable?

Answer

You want a slice() object:

index = slice(0, 2)
print(somelist[index])

slice() models the start, stop and stride values you can specify in the [start:stop:stride] subscription syntax, as an object.

From the documentation:

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default).

Under the covers, Python actually translates subscriptions to a slice() object when calling custom __getitem__ methods:

>>> class Foo(object):
...     def __getitem__(self, item):
...         return item
...
>>> Foo()[42:81:7]
slice(42, 81, 7)
>>> Foo()[:42]
slice(None, 42, None)

A viable alternative would be to store start and stop as separate values:

startindex = 0
stopindex = 2
print(somelist[start:stop])