Is there an expression for an infinite iterator?

PythonIteratorGeneratorInfinite Loop

Python Problem Overview


Is there a straight-forward expression that can produce an infinite iterator?

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


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

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 import-ing later doesn't count.


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

Python Solutions


Solution 1 - Python

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()

Solution 2 - Python

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.

Solution 3 - Python

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

g1=iter(lambda:0, 1)

Solution 4 - Python

Your OS may provide something that can be used as an infinite generator. Eg on linux

for i in (0 for x in open('/dev/urandom')):
    print i

obviously this is not as efficient as

for i in __import__('itertools').repeat(0)
    print i

Solution 5 - Python

Quite ugly and crazy (very funny however), but you can build your own iterator from an expression by using some tricks (without "polluting" your namespace as required):

{ print("Hello world") for _ in
    (lambda o: setattr(o, '__iter__', lambda x:x)
            or setattr(o, '__next__', lambda x:True)
            or o)
    (type("EvilIterator", (object,), {}))() } 

Solution 6 - Python

None that doesn't internally use another infinite iterator defined as a class/function/generator (not -expression, a function with yield). A generator expression always draws from anoter iterable and does nothing but filtering and mapping its items. You can't go from finite items to infinite ones with only map and filter, you need while (or a for that doesn't terminate, which is exactly what we can't have using only for and finite iterators).

Trivia: PEP 3142 is superficially similar, but upon closer inspection it seems that it still requires the for clause (so no (0 while True) for you), i.e. only provides a shortcut for itertools.takewhile.

Solution 7 - Python

Maybe you could use decorators like this for example:

def generator(first):
    def wrap(func):
        def seq():
            x = first
            while True:
                yield x
                x = func(x)
        return seq
    return wrap

Usage (1):

@generator(0)
def blah(x):
    return x + 1

for i in blah():
    print i

Usage (2)

for i in generator(0)(lambda x: x + 1)():
    print i

I think it could be further improved to get rid of those ugly (). However it depends on the complexity of the sequence that you wish to be able to create. Generally speaking if your sequence can be expressed using functions, than all the complexity and syntactic sugar of generators can be hidden inside a decorator or a decorator-like function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhugomgView Question on Stackoverflow
Solution 1 - PythonKatrielView Answer on Stackoverflow
Solution 2 - PythonncoghlanView Answer on Stackoverflow
Solution 3 - Pythonuser237419View Answer on Stackoverflow
Solution 4 - PythonJohn La RooyView Answer on Stackoverflow
Solution 5 - PythonThomas BaruchelView Answer on Stackoverflow
Solution 6 - Pythonuser395760View Answer on Stackoverflow
Solution 7 - PythonjulxView Answer on Stackoverflow