Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a list using a variable, in Python

Tags:

python

list

slice

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?

like image 811
robintw Avatar asked May 13 '12 16:05

robintw


People also ask

Can you use variable in Slice Python?

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.

How do you slice a value in a list in Python?

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 .

How does slicing work in Python list?

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.

Can we do slicing in list?

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.


2 Answers

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

like image 114
mata Avatar answered Sep 21 '22 16:09

mata


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.

like image 37
Mark Byers Avatar answered Sep 19 '22 16:09

Mark Byers