Is there an expression for an infinite iterator? Is there an expression for an infinite iterator? python python

Is there an expression for an infinite iterator?


itertools provides three infinite iterators:

I don't know of any others in the standard library.


Since you asked for a one-liner:

__import__("itertools").count()


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.


you can iterate over a callable returning a constant always different than iter()'s sentinel

g1=iter(lambda:0, 1)