Does count() generate an error if it cannot find any items?


#1

Question

In this exercise, count() is used to find the number of items in a list. If the item being counted isn’t in the list, will count() return an error?

Answer

No, count() will not return an error if the item passed to the function is not found. The count() function will return a value of 0. This is shown in the example code below. The first two items passed to count() are present in the vehicles list. The third item is not present in the list at all.

vehicles = ['car', 'truck', 'car', 'van', 'car', 'van']

# Returns value of 3
cars = vehicles.count('car')

# Returns value of 2
vans = vehicles.count('van')

# Returns value of 0
suvs = vehicles.count('suv')