Access multiple elements of list knowing their index
You can use operator.itemgetter
:
from operator import itemgetter
a = [-2, 1, 5, 3, 8, 5, 6]
b = [1, 2, 5]
print(itemgetter(*b)(a))
# Result:
(1, 5, 5)
Or you can use numpy:
import numpy as np
a = np.array([-2, 1, 5, 3, 8, 5, 6])
b = [1, 2, 5]
print(list(a[b]))
# Result:
[1, 5, 5]
But really, your current solution is fine. It's probably the neatest out of all of them.
Python: access multiple elements in list
Simply contact the sub-lists, like:
result = l[:1] + l[2:]
output:
['shanya', 1, False, 'test', 2, 3.3, True, '3', '4.0']
Find index for multiple elements in a long list
First create a dictionary containing in the index location of each item in the list (you state that all items are unique, hence no issue with duplicate keys).
Then use the dictionary to look up each item's index location which is average time complexity O(1).
my_list = ['ab', 'sd', 'ef', 'de']
d = {item: idx for idx, item in enumerate(my_list)}
items_to_find = ['sd', 'ef', 'sd']
>>> [d.get(item) for item in items_to_find]
[1, 2, 1]
Explicitly select items from a list or tuple
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.
How to find the indices of items in a list, which are present in another list?
N = []
for i in range(len(L)):
if L[i] in R:
N.append(i)
or with a generator
N = [i for i in range(len(L)) if L[i] in R]
or with arrays
import numpy as np
N=np.where(np.isin(L,R))
Related Topics
Find All Occurrences of a Key in Nested Dictionaries and Lists
Sending "User-Agent" Using Requests Library in Python
How to Configure Chromedriver to Initiate Chrome Browser in Headless Mode Through Selenium
Python None Comparison: Should I Use "Is" or ==
How to Merge a List of Dicts into a Single Dict
How to Pass Another Entire Column as Argument to Pandas Fillna()
Python - Pip Install Trouble Shooting - Permissionerror: [Winerror 5] Access Is Denied
Why Is the Id of a Python Class Not Unique When Called Quickly
Python Windows Authentication Username and Password Is Not Working
What Is the Best Project Structure for a Python Application
Correct Way to Try/Except Using Python Requests Module
Pandas Loc VS. Iloc VS. at VS. Iat
How to Split Text in a Column into Multiple Rows
Remove Unwanted Parts from Strings in a Column
Using 'Try' VS. 'If' in Python
Run Linux Grep Command from Python Subprocess
Python3 Flask Asyncio Subprocess in Route Hangs
Typeerror: Unsupported Operand Type(S) for -: 'Str' and 'Int'