In Python, how do I index a list with another list?

PythonListIndexing

Python Problem Overview


I would like to index a list with another list like this

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]

and T should end up being a list containing ['a', 'd', 'h'].

Is there a better way than

T = []
for i in Idx:
    T.append(L[i])

print T
# Gives result ['a', 'd', 'h']

Python Solutions


Solution 1 - Python

T = [L[i] for i in Idx]

Solution 2 - Python

If you are using numpy, you can perform extended slicing like that:

>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'], 
      dtype='|S1')

...and is probably much faster (if performance is enough of a concern to to bother with the numpy import)

Solution 3 - Python

A functional approach:

a = [1,"A", 34, -123, "Hello", 12]
b = [0, 2, 5]

from operator import itemgetter

print(list(itemgetter(*b)(a)))
[1, 34, 12]

Solution 4 - Python

T = map(lambda i: L[i], Idx)

Solution 5 - Python

I wasn't happy with any of these approaches, so I came up with a Flexlist class that allows for flexible indexing, either by integer, slice or index-list:

class Flexlist(list):
    def __getitem__(self, keys):
        if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
        return [self[k] for k in keys]

Which, for your example, you would use as:

L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]

print(T)  # ['a', 'd', 'h']

Solution 6 - Python

You could also use the __getitem__ method combined with map like the following:

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
res = list(map(L.__getitem__, Idx))
print(res)
# ['a', 'd', 'h']

Solution 7 - Python

L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h'] 
for keys in index:
	print(L[keys])

I would use a Dict add desired keys to index

Solution 8 - Python

My problem: Find indexes of list.

L = makelist() # Returns a list of different objects
La = np.array(L, dtype = object) # add dtype!
for c in chunks:
    L_ = La[c] # Since La is array, this works.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel AndrénView Question on Stackoverflow
Solution 1 - PythonvanView Answer on Stackoverflow
Solution 2 - PythonPaulView Answer on Stackoverflow
Solution 3 - PythonPadraic CunninghamView Answer on Stackoverflow
Solution 4 - PythonmmxView Answer on Stackoverflow
Solution 5 - PythonjedwardsView Answer on Stackoverflow
Solution 6 - PythonDavidView Answer on Stackoverflow
Solution 7 - Pythonuser4749532View Answer on Stackoverflow
Solution 8 - PythonHunaphuView Answer on Stackoverflow