How to Find an Element in a Python List

Python List index() 

list.index(element, start, end)

Find the index of the element

Example 1:

vowels = ['a', 'e', 'i', 'o', 'i', 'u']

index = vowels.index('e')
print('The index of e:', index)

index = vowels.index('i')
print('The index of i:', index)

Example 2: Checking if something is inside
 

3 in [1, 2, 3] # => True

Example 3:
Python3 program to Find elements of a
list by indices present in another list

def findElements(lst1, lst2):
return [lst1[i] for i in lst2]

lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))

Using numpy

import numpy as np

def findElements(lst1, lst2):
return list(np.array(lst1)[lst2])

lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))

Using itemgetter()
 

from operator import itemgetter

def findElements(lst1, lst2):
return list((itemgetter(*lst2)(lst1)))

lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))

Using Python map()
 

def findElements(lst1, lst2):
return list(map(lst1.__getitem__, lst2))

lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))

I hope you get an idea about Finding the index of an item in a list.


#py  #python 

How to Find an Element in a Python List
1.10 GEEK