1-liner to iterate over infinite sequence of integers?

Erik Max Francis max at alcyone.com
Thu Oct 13 18:53:27 EDT 2005


Fredrik Lundh wrote:

> 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

The negative integers are being descriminated against!  I demand justice!

	def integers():
	    yield 0
	    x = 1
	    while True:
	        yield x
	        yield -x
	        x += 1

... which is also not a bad demonstration of how the integers are 
countably infinite.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   War can only be abolished through war, and in order to get rid of the
   gun it is necessary to take up the gun. -- Mao Zedong, 1898-1976



More information about the Python-list mailing list