1-liner to iterate over infinite sequence of integers?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Oct 13 18:38:39 EDT 2005


On Thu, 13 Oct 2005 13:31:13 -0400, Neal Becker wrote:

> I can do this with a generator:
> 
>     def integers():
>         x = 1
>         while (True):
>             yield x
>             x += 1
> 
> for i in integers(): 
> 
> Is there a more elegant/concise way?

Others have given answers involving xrange() and itertools.count(), but I
thought I'd just mention that in my opinion, what you have written is
pretty elegant and concise and best of all, doesn't have the same problems
xrange() and itertools.count() have when then hit maxint. Not everything
needs to be a one-liner or a mysterious blackbox.

You could even modify your function to take start and step arguments:

def integers(start=1, step=1):
    x = start
    while True:
        yield x
        x += step

for odd in integers(step=2):
    print odd

for even in integers(0, 2):
    print even

etc.


-- 
Steven.




More information about the Python-list mailing list