Index
The index()
function in Python searches lists. We pass it a value, and it returns the index where that value is found. If no value is found, it throws an error.
With count, we count the matching elements in a list. Like index()
this loops through and tests each element in a linear way. List
provides no rindex method.
This example shows how the index()
method searches a list. If no value is found, we get an Error. We can handle this in a try-except
block (but this is not ideal).
for
-loop instead of index()
.for
-loop, we can more elegantly handle cases where the value is not found. This avoids the ValueError
.# Input list. values = ["uno", "dos", "tres", "cuatro"] # Locate string. n = values.index("dos") print(n, values[n]) # Locate another string. n = values.index("tres") print(n, values[n]) # Handle nonexistent string. try: n = values.index("?") # Not reached. print(n) except: # Value not found. print("Not found")1 dos 2 tres Not found
Count
This method does not return the number of elements in the list. Instead it counts a specific element. As an argument, pass the value of the element we wish to count.
count()
loops through all the elements and keeps track of the count. It then returns this value.names = ['a', 'a', 'b', 'c', 'a'] # Count the letter a. value = names.count('a') print(value)3
What is the fastest way to search a list? Given that searching a list is common done, learning the best way to do this is beneficial.
index()
method. Index()
raises an exception if no match is found.for
-loop with a range. This code does not raise an exception.for
-loop that tests each string
element.Index()
is likely optimized at a low level in Python. I suggest you prefer index()
for list searching.import time values = ["Augustus", "Tiberius", "Caligula", "Claudius"] print(time.time()) # Version 1: index. i = 0 while i < 10000000: v = values.index("Caligula") i += 1 print(time.time()) # Version 2: for-range. i = 0 while i < 10000000: v = 0 for n in range(0, len(values)): if values[n] == "Caligula": v = n break i += 1 print(time.time())1362429980.178 1362429984.018 index() = 3.84 s 1362429994.569 for = 10.55 s
Consider the count()
method. If we were to keep track of the items added to the list as we add them, we could compute counts without a loop. This would be faster.
With index and count, we have declarative (function-based) ways of testing the elements of a list. We can search for matching elements (and get an index, or the sum of matches).