title: Python: check if object exists in generator
body: <p>I had a bug which was caused by the changing result of checking "if x in generator"</p>
  
  <pre><code>def primes(upper_limit):
      for n in range(2, upper_limit):
          if all(n % i &gt; 0 for i in range(2, n)):
              yield n
  
  first_hundred_primes = primes(100)
  
  print(5 in first_hundred_primes)
  print(5 in first_hundred_primes)
  print(5 in first_hundred_primes)
  print(5 in first_hundred_primes)
  print(5 in first_hundred_primes)
  </code></pre>
  
  <p>This gives the output:</p>
  
  <pre><code>True
  False
  False
  False
  False
  </code></pre>
  
  <p>I'm assuming one isn't meant to check if an object exists in a generator, but if this is the case why doesn't it throw some error, and why does this work?</p>
  
  <pre><code>&gt;&gt;&gt; hundred_generator = range(1,100)
  &gt;&gt;&gt; 50 in hundred_generator
  True
  &gt;&gt;&gt; 50 in hundred_generator
  True
  &gt;&gt;&gt; 50 in hundred_generator
  True
  </code></pre>
  
  <p>I usually turn the generator into a set before I'm checking if some object exists in it (to speed up checking) and this fixes the problem, but I would very much like to know what's going on here?</p>