Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grabbing specific indices of a list [duplicate]

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

like image 952
sihrc Avatar asked Jan 13 '23 19:01

sihrc


1 Answers

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']
like image 69
TerryA Avatar answered Jan 22 '23 02:01

TerryA