Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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']
like image 900
Daniel Andrén Avatar asked Oct 04 '22 13:10

Daniel Andrén


People also ask

Does indexing work with lists in Python?

Note. python lists are 0-indexed. So the first element is 0, second is 1, so on.

How do you pass a list of indexes in Python?

We can use the index() function to get the index of an element in a list by passing the element as an argument in the function. In for loop we iterate through each of the elements by incrementing a counter and find a match for the searched element.

How do you put a list inside another list?

Use the extend() Method to Append a List Into Another List in Python. Python has a built-in method for lists named extend() that accepts an iterable as a parameter and adds it into the last position of the current iterable. Using it for lists will append the list parameter after the last element of the main list.


2 Answers

T = [L[i] for i in Idx]
like image 69
van Avatar answered Oct 08 '22 09:10

van


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)

like image 43
Paul Avatar answered Oct 08 '22 08:10

Paul