Slicing a list using a variable, in Python

39,850

Solution 1

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

Solution 2

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.

Solution 3

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]

Solution 4

>>> a=range(10)
>>> i=[2,3,4]

>>> a[i[0]:i[-1]]
range(2, 4)

>>> list(a[i[0]:i[-1]])
[2, 3]

Solution 5

I ran across this recently, while looking up how to have the user mimic the usual slice syntax of a:b:c, ::c, etc. via arguments passed on the command line.

The argument is read as a string, and I'd rather not split on ':', pass that to slice(), etc. Besides, if the user passes a single integer i, the intended meaning is clearly a[i]. Nevertheless, slice(i) will default to slice(None,i,None), which isn't the desired result.

In any case, the most straightforward solution I could come up with was to read in the string as a variable st say, and then recover the desired list slice as eval(f"a[{st}]").

This uses the eval() builtin and an f-string where st is interpolated inside the braces. It handles precisely the usual colon-separated slicing syntax, since it just plugs in that colon-containing string as-is.

Share:
39,850
danjarvis
Author by

danjarvis

I'm a PhD student at the Institute for Complex Systems Simulation at the University of Southampton, UK studying complexity in Remote Sensing. As part of my work I am heavily involved in Remote Sensing and GIS technologies - particularly ENVI/IDL programming and ArcGIS scripting using Python. My academic website shows some examples of my work, and links to some of the software I have written.

Updated on February 29, 2020

Comments

  • danjarvis
    danjarvis over 4 years

    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?

  • chill_turner
    chill_turner almost 7 years
    My use case involved some detailed parsing of html, trying to find the last element in this html table. Code looked like last_row = list(reversed(parsed_html_rows[-2:-1])) In code review we realized i had a number of these 'magic ranges' in the code for plucking out various stuff. Giving a name to them makes it easier for me and the reviewer.. last_row_indices = slice(-2, -1) and last_row = list(reversed(rows[last_row_indices])) # no more wtf'ing about why -2:-1
  • Nihir
    Nihir about 2 years
    10 years late to the game but the tuple solution works like a charm. Context: working with multi-dimensional arrays/tensors in numpy/pytorch