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 1.
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.
Looks like you’ve used the name, item, a few times too often. In your code, 2 is passed to your function as the argument to be assigned to your item parameter. However, you immediately reassign item the value 0.
Then in your for statement you use item as your iterator variable. First iteration: item is assigned the first value in lst, so 2. You then use this: item = item+1, so item is now assigned 3. This process continues until you’ve iterated the entire lst, assigning item a value of 3.
Since 3 is not greater than n which is also assigned 3 from the argument passed in at the function call, False is returned.
That’s what is happening, so how do you fix it? You want to count how many times item appears in lst, and then compare that count to n returning True if the count is greater than n, and False otherwise.