Slicing a list using a variable, in Python
Why does it have to be a single variable? Just use two variables:
i, j = 2, 4
a[i:j]
If it really needs to be a single variable you could use a tuple.
With the assignments below you are still using the same type of slicing operations you show, but now with variables for the values.
a = range(10)
i = 2
j = 4
then
print a[i:j]
[2, 3]
that's what slice()
is for:
a = range(10)
s = slice(2,4)
print a[s]
That's the same as using a[2:4]
.