I'm currently doing a projecteuler problem, which requires finding the sum of all the primes below two million.

I have a primitive function which determines whether or not a number is prime. This function is incorporated into the below function to produce a list with all the primes below the target:

def prime_target(target):
    list = []
    i = 0
    while i <= target:
        i += 1
        if is_prime(i) == True:
            list.append(i)
            print len(list), list[-1]

I know this isn't efficient, but it's a quick and dirty method.

However, when I come to sum(list) in a later part of the code, I get the following:

Traceback (most recent call last):
  File "euler-sum-primes.py", line 32, in <module>
    total = sum(list)
TypeError: 'type' object is not iterable

But the list contains integers... and what is "type" type? I had a look through the documentation to find the answer, but it seems like I must be missing something obvious.

Any help much appreciated.

Ok, so sum(list) works if it is inside the function, but returns a type error if it is outside the function.

Does this seems strange?

Well, 1) list is the name of a standard type in python (the type of list objects). A type is just a particular kind of object. 2) Since list is a standard name, it should be avoided as the name of a variable (it's not an error, but it's a bad idea), so the list that you're using in your function should be given another name, like plist . 3) Assuming you do this, the variable plist is local to the function's body. It doesn't exist in the global namespace. Note that your function doesn't return any value, so a good idea would be to add an instruction return plist at the end of the body. 4) Assuming you do this, you can then write plist = prime_target(target) at global level, and this defines a global variable plist (which could be given another name). You can then compute sum(plist) !

Not really that important, but just so you know: if is_prime(i) == True: , the "== True" is redundant there since it already returns a boolean. Change it to if is_prime(i): .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.