1-liner to iterate over infinite sequence of integers?
Fredrik Lundh
fredrik at pythonware.com
Thu Oct 13 14:01:35 EDT 2005
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?
depends on your definition of "integers":
xrange(sys.maxint) # 0-based
xrange(1, sys.maxint) # 1-based
gives you a sequence-like object that generates all positive Python
integers (no long integers)
itertools.count() # 0-based
itertools.count(1) # 1-based
gives you an iterator that generates all Python integers (the behaviour
when it exceeds sys.maxint doesn't seem to be defined, but 2.4 wraps
around to -(sys.maxint+1))
</F>
More information about the Python-list
mailing list