hugomg hugomg - 1 year ago 68
Python Question

Is there an expression for an infinite generator?

Is there a straight-forward generator expression that can yield infinite elements?

This is a purely theoretical question. No need for a "practical" answer here :)

For example, it is easy to make a finite generator:

my_gen = (0 for i in xrange(42))

However, to make an infinite one I need to "pollute" my namespace with a bogus function:

def _my_gen():
while True:
yield 0
my_gen = _my_gen()

Doing things in a separate file and
-ing later doesn't count.

I also know that
does exactly this. I'm curious if there is a one-liner solution without that.

Answer Source
for x in iter(int, 1): pass
  • Two-argument iter = zero-argument callable + sentinel value
  • int() always returns 0

Therefore, iter(int, 1) is an infinite iterator. There are obviously a huge number of variations on this particular theme (especially once you add lambda into the mix). One variant of particular note is iter(f, object()), as using a freshly created object as the sentinel value almost guarantees an infinite iterator regardless of the callable used as the first argument.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download