Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Native infinite range? [duplicate]

Tags:

Does python have a native iterable of the infinite integer series?

I've tried range(float('inf')) and iter(int), but neither work.

I can obviously implement my own generator along the lines of

def int_series(next=1):     while True:         next += 1         yield next 

but this feels like something which should already exist.

like image 481
jackweirdy Avatar asked Apr 07 '14 13:04

jackweirdy


2 Answers

Yes. It's itertools.count:

>>> import itertools >>> x = itertools.count() >>> next(x) 0 >>> next(x) 1 >>> next(x) 2 >>> # And so on... 

You can specify start and step arguments, though stop isn't an option (that's what xrange is for):

>>> x = itertools.count(3, 5) >>> next(x) 3 >>> next(x) 8 >>> next(x) 13 
like image 193
user2357112 supports Monica Avatar answered Sep 20 '22 13:09

user2357112 supports Monica


You can use itertools.count for this.

for x in itertools.count():     # do something with x infinite times 

If you don't want to use the integer returned by count(), then better use itertools.repeat:

for _ in itertools.repeat(None):      # do something infinite times 
like image 37
Ashwini Chaudhary Avatar answered Sep 19 '22 13:09

Ashwini Chaudhary