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.
Probably the closest to what you are looking for is
itemgetter
(or look here for Python 2 docs):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.:
Something like this?
Usage:
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.
And then you could call the function with:
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.If you can use
numpy
, you can do just that:numpy.array
is very similar tolist
, just that it supports more operation, such as mathematical operations and also arbitrary index selection like we see here.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:Of course it would also work for a string...