Here are two seemingly equivalent versions of a function for filtering out the primes from a list of numbers.
Version 1
def prime (mylist):
for i in range(2, 8):
return filter(lambda x: x == i or x % i, mylist)
Version 2
def prime2 (mylist):
nums = mylist
for i in range(2, 8):
nums = filter(lambda x: x == i or x % i, nums)
return nums
print prime([2,3,4,5,6,7,8,9,10,11,12,13,14,15])
>> [2, 3, 5, 7, 9, 11, 13, 15]
print prime2([2,3,4,5,6,7,8,9,10,11,12,13,14,15])
>> [2, 3, 5, 7, 11, 13]
Version 1 returns erroneous results. Why?
The first version only tests
i == 2. In other words, it only tests whether 2 is a factor, instead of testing all integers from 2 to 7 as you intended. This is why it will (correctly) filter out all even numbers but will (wrongly) leave the odd ones which are not prime, like 9 and 15. Try this to see it explicitly: