How is `:` interpreted?

Viewed 74

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!

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]
Related