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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With