C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: For programs where you need more control, consider using a for-loop instead of index().
forInfo: With a for-loop, we can more elegantly handle cases where the value is not found. This avoids the ValueError.
Python program that uses index
# 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")
Output
1 dos
2 tres
Not found
Note: Internally count() loops through all the elements and keeps track of the count. It then returns this value.
Python program that uses count
names = ['a', 'a', 'b', 'c', 'a']
# Count the letter a.
value = names.count('a')
print(value)
Output
3
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.
Python program that times 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())
Output
1362429980.178
1362429984.018 index() = 3.84 s
1362429994.569 for = 10.55 s