Q:

Why doesn't generating primes in Python using sets in this way work?

I have a standard algorithm that I use to generate prime numbers (probably not the most efficient but it works as well as I need it to) and I thought I'd optimise it a little by using sets instead of lists. However when I use a set I get numbers such as 143 and 989 which aren't prime and I'm not sure why this is. Below is my standard code that I use to generate primes with ''' marking where I would use a set instead of a list.
import math

prime = [2, 3]                        # prime = set([1, 2])    

def prime_checker(a):
    b = int(math.sqrt(a)) + 1
    for j in prime:
        if a % j == 0:
            return False
        if j > b:
            break   

for i in range (5, 100000, 2):
    if prime_checker(i) != False:
        prime.append(i)               # prime.add(i)

For some reason this always seems to work if I only look for primes less than 100, but once I extend this bound I start getting non-primes.

A:

When you're using set you're iterating over the primes in random order. That means that even first prime you process could be greater than b which causes the loop to terminate and number to added to result.
If you remove the early break you'll get the same result:
def prime_checker(a):
    #b = int(math.sqrt(a)) + 1
    for j in prime:
        if a % j == 0:
            return False
        #if j > b:
        #    break   

A:

Sets are unordered, but (due to implementation details in the standard Python interpreter CPython), sets that only include sequential (or nearly sequential) small integers will often have their values in order, especially if that's the order they were added to the set.
However, as the contents of a set become more sparse (as a set of primes will), the chances of larger values occurring between the smaller items in iteration order increases. Your algorithm relies on the order of the primes in your prime sequence, since you stop looping after you see the first prime larger than sqrt(a). So as the set grows, it's more and more likely that your prime check will not work correctly.
It's not clear to me why you'd want to use a set anyway. You're not doing any membership testing against the prime list, so a list works just as well as a set. If you need a set for later, you may want to generate it after you've finished building the list (or use a different algorithm).

