Explicitly select items from a list or tuple
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping
--
Chapters
00:00 Question
00:53 Accepted answer (Score 203)
01:44 Answer 2 (Score 58)
01:57 Answer 3 (Score 16)
02:16 Answer 4 (Score 11)
02:46 Thank you
--
Full question
https://stackoverflow.com/questions/6632...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #select #indexing #tuples
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping
--
Chapters
00:00 Question
00:53 Accepted answer (Score 203)
01:44 Answer 2 (Score 58)
01:57 Answer 3 (Score 16)
02:16 Answer 4 (Score 11)
02:46 Thank you
--
Full question
https://stackoverflow.com/questions/6632...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #select #indexing #tuples
#avk47
ACCEPTED ANSWER
Score 209
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
I compared the answers with python 2.5.2:
19.7 usec:
[ myBigList[i] for i in [87, 342, 217, 998, 500] ]20.6 usec:
map(myBigList.__getitem__, (87, 342, 217, 998, 500))22.7 usec:
itemgetter(87, 342, 217, 998, 500)(myBigList)24.6 usec:
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
Note that in Python 3, the 1st was changed to be the same as the 4th.
Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:
>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])
The tuple doesn't work the same way as those are slices.
ANSWER 2
Score 61
What about this:
from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')
ANSWER 3
Score 18
Maybe a list comprehension is in order:
L = ['a', 'b', 'c', 'd', 'e', 'f']
print [ L[index] for index in [1,3,5] ]
Produces:
['b', 'd', 'f']
Is that what you are looking for?
ANSWER 4
Score 12
It isn't built-in, but you can make a subclass of list that takes tuples as "indexes" if you'd like:
class MyList(list):
def __getitem__(self, index):
if isinstance(index, tuple):
return [self[i] for i in index]
return super(MyList, self).__getitem__(index)
seq = MyList("foo bar baaz quux mumble".split())
print seq[0]
print seq[2,4]
print seq[1::2]
printing
foo
['baaz', 'mumble']
['bar', 'quux']