2

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)
El Bert
  • 2,958
  • 1
  • 28
  • 36
  • 1
    if you know the indexes you want, why not just use slicing? – MattDMo Jan 08 '14 at 20:31
  • Have you attempted this yourself? – Totem Jan 08 '14 at 20:31
  • @MattDMo slicing would work perfectly and can even work for non consecutive indexes if using the `iterable[start:end:step]` notation. Thanks just didn't thought about it ! – El Bert Jan 08 '14 at 20:37
  • also... not sure the context, but maybe see this: http://stackoverflow.com/questions/19503455/caching-a-generator if part of your issue is that you don't know if the input is an iterable or not... – Corley Brigman Jan 08 '14 at 20:39

1 Answers1

2

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

chepner
  • 497,756
  • 71
  • 530
  • 681