Python Code Challenges involving Lists, Q4

Hi there,

I’m working on this challenge:

Question 4 is the following:

  1. Define the function to accept three parameters, a list of numbers, a number to look for, and a number for the number of instances
  2. Count the number of occurrences of item (the second parameter) in lst (the first parameter)
  3. If the number of occurrences is greater than n (the third parameter), return True . Otherwise, return False

In the solution I’ve seen that I could use

def more_than_n(lst, item, n):
  if lst.count(item) > n:
    return True
    return False

However, I was trying to build a loop myself and it does run but doesn’t return the desired result. Where’s my mistake, how can I get to the same result as the code above?

def more_than_n(lst, item, n):
  count = 0
  for i in (0,len(lst)-1):
    if lst[i] == item:
      count += 1
      count += 0
  if count > n:
    return True
    return False

The following should return True but returns False with my code:

print(more_than_n([2, 4, 6, 2, 3, 2, 1, 2], 2, 3))

Hello @chip1578684310, welcome to the forums! Notice how you’re just iterating through the tuple (0, len(lst)-1)? I imagine you’re actually looking to loop through the range() of numbers…

Thanks @codeneutrino, I see it now!

1 Like