1-liner to iterate over infinite sequence of integers?

N

Neal Becker

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?
 
W

Will McGugan

Neal said:
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?

import itertools
for i in itertools.count():
print i


Will McGugan
 
S

Steven D'Aprano

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.
 
P

Paul Rubin

Steven D'Aprano said:
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.

When you say "problems" with xrange or itertools.count hitting maxint,
the correct word is "bugs". The right thing to do with library bugs
is fix them, not clutter up your application code to circumvent them.
xrange, at least, raises an error if you give it too large an
argument, but what itertools.count does is just plain dangerous.

I just opened SF bug 1326277 about itertools.count.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top