Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is `:` interpreted? [duplicate]

Tags:

python

I know "how" to use the : operator to extract data from a list in python.

Eg:

l = [1,2,3]
print(l[0:1])
print(l[-1:])

Yields:

[1]
[3]

But, how does python literally interpret the :?

Why can't I set a variable equal to : and then call it?

Eg:

x = :
print(l[x])

Would yield:

[1, 2, 3]

Hoping someone who can go deeper on how python works can offer some insight.

Thanks!

like image 392
jason m Avatar asked Jun 07 '26 21:06

jason m


1 Answers

: is shorthand for the slice class. You can assign instances of that class to variables for what you're trying to:

>>> l = [1, 2, 3]
>>> l[1:3]
[2, 3]
>>> l[slice(1, 3)]
[2, 3]
>>> x = slice(0, 2)
>>> l[x]
[1, 2]
like image 87
kevingessner Avatar answered Jun 10 '26 11:06

kevingessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!