Given a list
a = range(10)
You can slice it using statements such as
a[1] a[2:4]
However, I want to do this based on a variable set elsewhere in the code. I can easily do this for the first one
i = 1 a[i]
But how do I do this for the other one? I've tried indexing with a list:
i = [2, 3, 4] a[i]
But that doesn't work. I've also tried using a string:
i = "2:4" a[i]
But that doesn't work either.
Is this possible?
Using the slice function to create a slice object can be useful if we want to save a specific slice object and use it multiple times. We can do so by first instantiating a slice object and assigning it to a variable, and then using that variable within square brackets.
You can generate a slice object using the built-in function slice() . If you want to repeatedly select the items at the same position, you only need to generate the slice object once. slice(start, stop, step) is equivalent to start:stop:step . If two arguments are specified, step is set to None .
With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.
As well as using slicing to extract part of a list (i.e. a slice on the right hand sign of an equal sign), you can set the value of elements in a list by using a slice on the left hand side of an equal sign. In python terminology, this is because lists are mutable objects, while strings are immutable.
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]
.
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.
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