Slicing a list using a variable, in Python

robintw picture robintw · May 13, 2012 · Viewed 31.2k times · Source

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?

Answer

mata picture mata · May 13, 2012

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