26

As far as I can tell, this is not officially not possible, but is there a "trick" to access arbitrary non-sequential elements of a list by slicing?

For example:

>>> L = range(0,101,10)
>>> L
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Now I want to be able to do

a,b = L[2,5]

so that a == 20 and b == 50

One way besides two statements would be something silly like:

a,b = L[2:6:3][:2]

But that doesn't scale at all to irregular intervals.

Maybe with list comprehension using the indices I want?

[L[x] for x in [2,5]]

I would love to know what is recommended for this common problem.

3
  • 6
    a,b = L[2],L[5]?
    – roippi
    Oct 2, 2013 at 1:18
  • 1
    @roippi - That does make it look simple, but I wanted to apply this directly to the output of a function that returns a list, without calling the function twice or re-assigning that to a variable and then grabbing.
    – beroe
    Oct 2, 2013 at 1:28
  • 1
    I'm inclined to say that your list comprehension is the best you can do. Or, if you don't need an actual list, use a generator expression, like in Shashank Gupta's answer (though if you only need it once, you could just put the genexp inline, rather than making a function to return it).
    – Blckknght
    Oct 2, 2013 at 2:07

5 Answers 5

34

Probably the closest to what you are looking for is itemgetter (or look here for Python 2 docs):

>>> L = list(range(0, 101, 10))  # works in Python 2 or 3
>>> L
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> from operator import itemgetter
>>> itemgetter(2, 5)(L)
(20, 50)
6
  • 2
    @justhalf: Well, itemgetter is very similar to Shashank's answer, except already included in the Python standard library.
    – John Y
    Oct 2, 2013 at 3:35
  • It is a nice solution toto, but I think the extra up votes are because it came in slightly sooner... I ultimately chose the one that doesn't require an import even though it mainly wrapped the OP in a function definition.
    – beroe
    Oct 2, 2013 at 14:04
  • 4
    @beroe: It's still getting more new votes even after you accepted the other answer, so the earlier time has nothing to do with it. I believe the reason my answer is getting more votes is that experienced Python programmers will usually prefer to use itemgetter than to define a new function. One import is shorter and simpler than one function definition.
    – John Y
    Oct 2, 2013 at 14:38
  • Makes sense. I like it as a solution. (I voted for it too ;^)
    – beroe
    Oct 2, 2013 at 18:42
  • For Python 3, the first line would change to >>> L = list(range(0, 101, 10)) to perform the "identical" operation. Jun 27, 2018 at 15:50
14

If you can use numpy, you can do just that:

>>> import numpy
>>> the_list = numpy.array(range(0,101,10))
>>> the_indices = [2,5,7]
>>> the_subset = the_list[the_indices]
>>> print the_subset, type(the_subset)
[20 50 70] <type 'numpy.ndarray'>
>>> print list(the_subset)
[20, 50, 70]

numpy.array is very similar to list, just that it supports more operation, such as mathematical operations and also arbitrary index selection like we see here.

2
  • 2
    I think the reason it is not the accepted answer is because (a) it has more bloat, and (b) it is less generalized. (a): numpy is a huge library, and this answer pulls the whole thing in. (Perhaps from numpy import array?) (b): numpy is specifically for mathematical operations, so is less familiar to folks who focus on, for instance, back-end web development. itemgetter is closer to "bare" Python that reaches a wider audience. Jun 27, 2018 at 15:49
  • 1
    from numpy import array will still load the whole numpy package, I believe. But you're right, this might be overkill if the list is not used for math operations.
    – justhalf
    Jun 27, 2018 at 18:08
11

Just for completeness, the method from the original question is pretty simple. You would want to wrap it in a function if L is a function itself, or assign the function result to a variable beforehand, so it doesn't get called repeatedly:

[L[x] for x in [2,5]]

Of course it would also work for a string...

["ABCDEF"[x] for x in [2,0,1]]
['C', 'A', 'B']
10

Something like this?

def select(lst, *indices):
    return (lst[i] for i in indices)

Usage:

>>> def select(lst, *indices):
...     return (lst[i] for i in indices)
...
>>> L = range(0,101,10)
>>> a, b = select(L, 2, 5)
>>> a, b
(20, 50)

The way the function works is by returning a generator object which can be iterated over similarly to any kind of Python sequence.

As @justhalf noted in the comments, your call syntax can be changed by the way you define the function parameters.

def select(lst, indices):
    return (lst[i] for i in indices)

And then you could call the function with:

select(L, [2, 5])

or any list of your choice.

Update: I now recommend using operator.itemgetter instead unless you really need the lazy evaluation feature of generators. See John Y's answer.

4
  • 1
    Do you think defining the function as select(lst, indices) and calling it as select(L, [2,5]) would be better?
    – justhalf
    Oct 2, 2013 at 1:47
  • @justhalf Yeah that's possible as well, I'll make a note.
    – Shashank
    Oct 2, 2013 at 1:50
  • @Shashank quick question. the "*indices" argument it's just "*args" right? but with a different name? Jun 21, 2015 at 0:44
  • @HalcyonAbrahamRamirez Yes, exactly. :) This is a very old answer however, and I would recommend using operator.itemgetter instead unless the lazy-evaluation feature of generators is required.
    – Shashank
    Jun 21, 2015 at 20:35
1

None of the other answers will work for multidimensional object slicing. IMHO this is the most general solution (uses numpy):

numpy.ix_ allows you to select arbitrary indices in all dimensions of an array simultaneously.

e.g.:

>>> a = np.arange(10).reshape(2, 5) # create an array
>>> a
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
>>> ixgrid = np.ix_([0, 1], [2, 4]) # create the slice-like grid
>>> ixgrid
(array([[0],
       [1]]), array([[2, 4]]))
>>> a[ixgrid]                       # use the grid to slice a
array([[2, 4],
       [7, 9]])
1
  • 1
    Yes it is too bad python doesn’t have better basic support of array-type data without requiring numpy
    – beroe
    Jun 5, 2018 at 3:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.