Python function to count divisible numbers in a list?


I need to write a python function that takes a list as the input and calculates the number of numbers divisible by some other number, n. This is the code I have so far:

enter image description here

Could someone advice me on what approach to take, please?

I tried a for loop that finds the divisible numbers and adds them to a counter, but that is not working.

>Solution :

You’re returning the length of an integer, count, when you probably want to return the count itself:

def count_divisible(lst, n):
    count = 0
    for i in lst:
        if i % n == 0:
            count += 1
    return count

You can shorten your function and make it safer by checking each item is actually an int or a float:

def count_divisible_short_and_safe(lst: list, n: int) -> int:
    return len([x for x in lst if isinstance(x, (int, float)) and x % n == 0])

assert count_divisible_short_and_safe([2,3,4,5, "foo"], 2) == 2

Leave a Reply Cancel reply