4

Is there a way to grab specific indices of a list, much like what I can do in NumPy?

sample = ['a','b','c','d','e','f']
print sample[0,3,5]
>>>['a','d','f']

I've tried Googling this, but I couldn't find a good way to word my issue that resulted in relevant results...

martineau
  • 119,623
  • 25
  • 170
  • 301
sihrc
  • 2,728
  • 2
  • 22
  • 43
  • Yep sorry.. I couldn't manage to get the wording right to find it. Thank you for linking it! :( – sihrc Jul 28 '13 at 03:51
  • No problem, that happens. There are a quite a few choices over at the other answer; hope you find one you like. – Ray Toal Jul 28 '13 at 03:53

1 Answers1

9

You can use a list comprehension:

>>> sample = ['a','b','c','d','e','f']
>>> [sample[i] for i in (0, 3, 5)]
['a', 'd', 'f']

Or, something I quickly made:

>>> class MyList(list):
...     def __getitem__(self, *args):
...             return [list.__getitem__(self, i) for i in args[0]]
... 
>>> mine = MyList(['a','b','c','d','e','f'])
>>> print mine[0, 3, 5]
['a', 'd', 'f']
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • Ah yes! I forgot about those. I do wish there was a shorter way like there is in NumPy. BTW, I was going to use this for strings... I figured "".join([]) would do the trick, unless there's a better way. – sihrc Jul 28 '13 at 03:50
  • @sihrc Like create a string `'adf'`? Then join is the way to go ;) – TerryA Jul 28 '13 at 03:51
  • Yea.. I thought so. Thanks! @Haidro – sihrc Jul 28 '13 at 03:52