List index and count Examples
This page was last reviewed on Jul 13, 2023.
Dot Net Perls
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).
Tip For programs where you need more control, consider using a for-loop instead of index().
Info With a 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.
Note Internally 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)
Benchmark, index. 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.
Version 1 We test the index() method. Index() raises an exception if no match is found.
Version 2 In this version of the code we use a for-loop with a range. This code does not raise an exception.
Result In this test, the index method is far faster than the for-loop that tests each string element.
So 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
Performance, count. 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).
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 13, 2023 (edit).
© 2007-2024 Sam Allen.