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']
Note. python lists are 0-indexed. So the first element is 0, second is 1, so on.
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.
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.
T = [L[i] for i in Idx]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With