A common programming task is to search through a list or tuple looking for a particular entry in that list. If the entry exists then the index at which that entry is located can then be extracted and used elsewhere.
We can write a function to do this for us using the enumerate()
method on any iterable.
The enumerate()
function works on any iterable object and returns both a counter and the value of the item stored at each index in the iterable. You can convert the result to a list to view as a list of tuples.
>>> somelist = ['dog','cat','horse']
>>> enumlist = list(enumerate(somelist))
>>> print(enumlist)
# result is a list of tuples
[(0, 'dog'), (1, 'cat'), (2, 'horse')]
By adding the enumerate()
method into a standard for
loop, you can run through each item in a list to check whether the item you are searching for exists. If it exists then break
out of the loop and extract the index at which it is located.
def find_index(to_search,target):
""" return the index of an item in the iterable.
If item does not exist then return -1.
"""
for idx,value in enumerate(to_search):
if value == target:
break
else:
return -1
return idx
A few examples of this function in action:
>>> alist = ['read','write',3,[3,4,6]]
>>> print(find_index(alist,'write'))
1 # exist at index position 1
>>> print(find_index(alist,4))
-1 # does not exist in list
>>> print(find_index(alist,'3'))
-1 # does not exist as target here is string not integer
>>> atuple = ('read','write','read and write')
>>> print(find_index(atuple,'read'))
0