Skip to content
Advertisement

len(list) does not provide any result, whereas print(list) does. Why?

my homework is building number of prime number counting code. This is where I come so far.

def count_primes(num):
    prime_list = []
    for n in range(0,num+1):
        if n >1: 
            for i in range(2,n):
                if n%i==0: 
                    break
            else: 
                prime_list.append(n)
    print(prime_list)

Check

count_primes(100)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

I initially thought that using ‘len’ would provide the number of prime numbers. But when I change ‘print’ to ‘len’ Nothing happened.

def count_primes(num):
    prime_list = []
    for n in range(0,num+1):
        if n >1: 
            for i in range(2,n):
                if n%i==0: 
                    break
            else: 
                prime_list.append(n)
    len(prime_list)

I would appreciate if you show me some insight What I did I wrong.

Advertisement

Answer

First of all, your syntax is wrong, but I assume that was because of copying the code to the question.

The problem is that the len() function returns the value (i.e. the length). So you have to either capture that value in a variable or return that value itself.

Example:

def count_primes(num):
    prime_list = []
    for n in range(0,num+1):
        if n >1: 
            for i in range(2,n):
                if n%i==0: 
                    break
            else: 
                prime_list.append(n)
    return len(prime_list) #Returns len() of prime_list

print(count_prime(50)) #Prints returned value

This will return the length of prime_list to the print function, which prints it out to the terminal.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement