Is it possible to count the occurrences of multiple items in a list using a single loop?


#1

Question

In this code challenge, we need to count the occurrences of two items in the same list. Is it possible to count the occurrences of multiple items in a list using a single loop?

Answer

Yes, this is absolutely possible. What you can do is, as you iterate over each element of the list, you can utilize if and elif statements to check if each element matches any of the values being counted.

We can do this for any number of values, as long as we have an if or elif statement for each one. For example, if we wanted to get the occurrences of three different values in a list in a single loop, it would look as follows.

# Values to find occurrences of
value1 = 1
value2 = 2 
value3 = 3

# Variables to keep track of each count
count1 = 0
count2 = 0
count3 = 0

# Iterate over the list one time,
# and for each element check if
# it matches any of our values.
# If so, increment its count.
for element in list:
  if element == value1:
    count1 += 1
  elif element == value2:
    count2 += 1
  elif element == value3:
    count3 += 1