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?
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 toNone
. Slice objects have read-only data attributesstart
,stop
andstep
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])
You can instead create a slice
object:
index = slice(0,2)
print(lst[index])
Be careful not to use list
as name to avoid shadowing the builtin list
function.
From the docs:
slice(start, stop[, step])
Return a slice object representing the set of indices specified by
range(start, stop, step)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With