Question

I want to retrieve specific indexes from an iterable. That would be equivalent to:

In [7]: def f():  
   ...:     return [1,2,3,4,5]  
In [8]: (_, x, _, y, _) =  f()  
In [9]: x, y  
Out[9]: (2, 4)

But I don't want to compute the iterable multiple times or it's very long and I don't want to write too many _s

My question is purely out of curiosity and I am actually using a local variables as shown above.

EDIT:

One solution is to simply use slicing with the notation iterable[start:end:step]:

In [24]: (x, y) =  f()[1:4:2]  
In [25]: x, y  
Out[25]: (2, 4)`

EDDIT BIS: Using slicing works if you need to retrieve every nth elements in an iterable but if you want elements at index 2,3 and 5,6 using operator.itemgetter(2,3,5,6)(lst) seems to be a better solution:

In [8]: operator.itemgetter(2,3,5,6)(range(10))
Out[8]: (2, 3, 5, 6)
Was it helpful?

Solution

One slightly roundabout way is to use the itemgetter function from the operator module.

 import operator
 m = operator.itemgetter(2,3)
 x, y = m([1,2,3,4,5])

The call to itemgetter creates a callable which takes an iterable L and returns L[2] and L[3].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top