To learn about lambdas I was following this tutorial, and ran into this example about calculating primes (python 2.x):
nums = range(2,50)
for i in range(2,8):
nums = filter(lambda x: x == i or x % i, nums)
print (list(nums))
prints
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
However, while trying this in python 3.4 it produced unexpected behavior:
nums = range(2,50)
for i in range(2,8):
nums = filter(lambda x: x == i or x % i , nums)
print(list(nums))
prints
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48]
I don't understand why there is a difference. I know filter returns a filter object in python 3 (instead of a list) but as far as I know that should not affect the outcome.
Removing the for loop produces the right result:
>>> nums = range(2,50)
>>> nums = filter(lambda x: x == 2 or x % 2, nums)
>>> nums = filter(lambda x: x == 3 or x % 3, nums)
>>> nums = filter(lambda x: x == 4 or x % 4, nums)
>>> nums = filter(lambda x: x == 5 or x % 5, nums)
>>> nums = filter(lambda x: x == 6 or x % 6, nums)
>>> nums = filter(lambda x: x == 7 or x % 7, nums)
>>> print(list(nums))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
I hope someone could enlighten me about this as I'm curious about what is going on.