Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use colon (:) in variable [duplicate]

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?

like image 915
giorgi shengelaia Avatar asked Nov 10 '16 15:11

giorgi shengelaia


2 Answers

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])
like image 121
Martijn Pieters Avatar answered Oct 21 '22 17:10

Martijn Pieters


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)

like image 44
Moses Koledoye Avatar answered Oct 21 '22 18:10

Moses Koledoye