An alternative that pushes the work to the C layer on CPython (the reference interpreter):
from operator import itemgetter
temp = ['a','b','c','d']
index_needed=[0,2]
output_list = itemgetter(*index_needed)(temp)
That returns tuple
of the values; if list
is necessary, just wrap in the list
constructor:
output_list = list(itemgetter(*index_needed)(temp))
Note that this only works properly if you need at least two indices; itemgetter
is variable return type based on how it's initialized, returning the value directly when it's passed a single key to pull, and a tuple
of values when passed more than one key.
It's also not particularly efficient for one-off uses. A more common use case would be if you had an iterable of sequences (typically tuple
s, but any sequence works), and don't care about them. For example, with an input list
of:
allvalues = [(1, 2, 3, 4),
(5, 6, 7, 8)]
if you only wanted the values from index 1 and 3, you could write a loop like:
for _, x, _, y in allvalues:
where you unpack all the values but send the ones you don't care about to _
to indicate the lack of interest, or you can use itemgetter
and map
to strip them down to what you care about before the unpack:
from future_builtins import map # Because Py2's map is terrible; not needed on Py3
for x, y in map(itemgetter(1, 3), allvalues):
The itemgetter
based approach doesn't care if you have more than four items in a given element of allvalues
, while manual unpacking would always require exactly four; which is better is largely based on your use case.