In this code challenge, we first need to obtain the number of occurrences of an item in a list. What ways are there to do this?
There are a few ways to count the occurrences of an item in a list. A few ways are as follows.
One way is to utilize the built-in
.count() method, which applies to a list, and takes in a value as its argument. It will return the number of times the value appears in the list. The syntax is as follows,
Another way to do this is using a loop. You can first start by initializing a variable to
0, which will keep track of the number of occurrences. The loop can iterate over each element of that list, and for each element, you can use an if statement to check whether that current element matches the value you are counting. If there is a match, increment the variable by
The implementation of the loop will not be shown here and will be left as a challenge for you to implement. Try to solve this exercise without using the
.count() method at first.