Why does the python filter do not overflow when it processes an infinite sequence?
<pre><code>def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n

def filt(n):
    return lambda x: x % n &gt; 0

def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(filt(n),it)
</code></pre>

<p>For example: ã3,5,7,9,11,13,15 ......ã<br>
If I have to take number 7 from this sequence I want to judge whether it is a prime number that must be divided in 3 and 5 to determine And 3,5 of these information must be stored up even if the inert load or the more information will be stored in the future will be more and more slow calculation of the actual experiment but in fact generate prime speed is not lower and the memory does not explode and I want to know what the internal principles </p>

<p>In Python 3, as your post is tagged, <code>filter</code> is a lazily-evaluated generator-type object. If you tried to evaluate that entire <code>filter</code> object with e.g. <code>it = list(filter(filt(n),it))</code>, you would have a bad time. You would have an equally bad time if you ran your code in Python 2, in which <code>filter()</code> automatically returns a list.</p>

<p>A filter on an infinite iterable is not inherently problematic, though, because you can use it in a perfectly acceptable way, like a <code>for</code> loop:</p>

<pre><code>it = filter(filt(n),it)
for iteration in it:
    if input():
        print(iteration)
    else:
        break
</code></pre>

python python-3.x functional-programming