title: Finding Primes with Modulo in Python
body: <p>I have been sweating over this piece of code -- which returns all the primes in a list:</p>
  
  <pre><code>primes = range(2, 20) 
  for i in range(2, 8): 
       primes = filter(lambda x: x == i or x % i, primes)
  
  print primes
  </code></pre>
  
  <p>It works... but I don't understand the role "<code>x == i or x % i</code>" plays in the whole thing.</p>
  
  <p>I also don't understand why the second range is only 2 to 7.</p>
  
  <p>I even created a Python implementation of the Sieve of Eratosthenes, hoping that might give me some insight, but it didn't.</p>
  
  <p>When I remove the <code>x % i</code> component, I would expect this code to give me the numbers common to both sets, but it does not:</p>
  
  <pre><code>nums = [2, 20] 
  for i in range(2, 8): 
       nums = filter(lambda x: x == i, nums)
  
  print nums
  </code></pre>
  
  <p>Why is this?</p>
  
  <p>Likewise, when I remove the <code>x == i</code> component, it returns the prime numbers from 11 to 19. </p>
  
  <pre><code>nums = range(2, 20) 
  
  for i in range(2, 8): 
       nums = filter(lambda x: x % i, nums)
  
  print nums
  </code></pre>
  
  <p>Again, I don't understand why it ignores all primes below 11.</p>
  
  <p>Next, I tried this:</p>
  
  <pre><code>nums = [13] 
  
  for i in range(2, 8): 
       nums = filter(lambda x: x % i, nums)
  
  print nums
  </code></pre>
  
  <p>Again, this makes no sense to me. The lambda is iterating over <code>x</code> in <code>nums</code> correct? And <code>i</code> is iterating over the range 2 to 7. So, aren't we taking <code>13 % i</code>... for 2 to 7? How does that result in "13"?</p>
  
  <p>Using the same logic as immediately above, I did the same thing with "13", but using <code>x == i</code> in the lambda. </p>
  
  <pre><code>for i in range(2, 8): 
       nums = filter(lambda x: x == i, nums)
  
  print nums
  </code></pre>
  
  <p>And as I expected, it returned an empty list -- which makes sense in my mind, because 13 never appears in the range of 2 to 7.</p>
  
  <p>For reference to anyone trying to help, this is the mindset I'm in when I work with <code>filter()</code> and lambdas:</p>
  
  <pre><code>a = range (1, 11)
  b = range (9, 20) 
  
  for i in filter(lambda x: x in a, b):
      print i,
  </code></pre>
  
  <p>This, of course, gives us "9 10". I know the structure of the loop is different, but hopefully it will help you see where my confusion lies.</p>
  
  <p>I have worked with <code>filter()</code> and lambdas somewhat extensively, so I thought I could figure it out, but I'm stumped! I just hope the answer isn't so blindingly obvious that I feel like an idiot...</p>