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

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
12 Likes
def more_frequent_item(lst, item1, item2):
  if lst.count(item1) >= lst.count(item2):
    return item1
  return item2
#Uncomment the line below when your function is done
print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3))
4 Likes

This is the code I wrote hope it helps everyone out

def more_frequent_item(lst,item1,item2):
 if(lst.count(item1 > lst.count(item2))):
    return item1
  else:
    return item2

Here’s a definitely longer way about it , but it works!

def more_frequent_item(lst,item1,item2):
  check1 = lst.count(item1)
  check2 = lst.count(item2)
  
  if check1 < check2:
    return item2
  elif check2 < check1:
    return item1
  elif check2 == check1:
    return item1
  
print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3))