-1

I'm trying to just print out the found primes. I want to add to the prime[], but I get a TypeError

line 63, in isprime
    primes += n
TypeError: 'int' object is not iterable

The code:

def isprime(n):
    primes = []
    if n == 1:
        print '1 is special'
        return False
    for x in range(2, n):
        if n%x == 0:
            print '{} equals {} x {}'.format(n, x, n // x)
            return False
    else:
        primes += n
        print (n, "is a prime number")
        return True

for n in range(1, 1000):
    isprime(n)
Vijayanand Premnath
  • 3,415
  • 4
  • 25
  • 42
  • 2
    maybe try `primes.append(n)` – Boo Radley Jul 01 '16 at 01:52
  • There are some important differences between `.append()` and `+= []`. See http://stackoverflow.com/questions/725782/in-python-what-is-the-difference-between-append-and Also, because `.append` is a method you can use it in a function to mutate a global list, you can't do that with `+=` unless you declare the list to be global. – PM 2Ring Jul 01 '16 at 01:59
  • FWIW, there are a couple of things you can do to make your prime test much more efficient. Note that there's not much point saving your primes like that, since the `primes` list will get cleared every time you call the function. However, there are a few ways that you can cache `n` so that you don't need to check the same number twice during a given run of the program. – PM 2Ring Jul 01 '16 at 04:22

2 Answers2

4

+= on a list is intended to concatenate one list to another. If you want to add a single element onto the end of the list, you can either do the straightforward:

primes.append(n)

or make a temporary list to allow the list concatenation operation to work (this approach is slower, and only trivially more concise, with greater memory churn involved; I highly recommend using .append unless you need to add more than one element at a time, in which case the += approach scales better for multielement list literals):

primes += [n]
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • You should maybe also mention `.extend`. – PM 2Ring Jul 01 '16 at 02:04
  • 1
    @PM2Ring: I suppose. `+=` and `extend` are identical in effect (and unlike with other types like `set`, there is no difference in type strictness; you can use either one with arbitrary iterables, where `set` operator overloads limit themselves to working with `set`/`frozenset`, not arbitrary iterables). `extend` is slightly slower in CPython as a consequence of the Python function call machinery getting invoked, where syntax based `+=` avoids it. Only real benefit to `extend` is that it doesn't involve assignment, so you can use it on globals without creating locals, or on lists inside tuples. – ShadowRanger Jul 01 '16 at 02:09
0

primes is a list, so to add n, which is an int, to it, you have to use the append method. Replace primes += n with primes.append(n).

edwinksl
  • 7,005
  • 4
  • 30
  • 36