Access Multiple Elements of List Knowing Their Index

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



Leave a reply



Submit