0

Is there any function in Python that provides an infinite series similar to generateSequence in Kotlin?

In Kotlin I can do something like:

generateSequence(1) { it + 1 }.take(5).forEach { println(it) }

Obviously this stops with an integer overflow error but I would like to do something similar in Python.

Iroh4526
  • 93
  • 1
  • 7
  • This SO thread will be of interest to you: https://stackoverflow.com/questions/5737196/is-there-an-expression-for-an-infinite-generator – Peter Leimbigler Nov 15 '18 at 02:46

2 Answers2

0

you can write a simple generator

def count(x):
    while True:
        yield x
        x += 1

for i in count(5):
    print(i)

of coarse this particular generator is builtin with itertools.count

import itertools
for i in itertools.count(5):
    print(i)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Use itertools.count() to get a count object that generates an infinite sequence of values.

You can take the first n items by explicitly retrieving the next item from the count object for the required number of times. Alternatively, and preferably, use itertools.islice() to take the first n items.

Mirroring your example, to take the first 5 values of the sequence using explicit iteration:

from itertools import count

c = count(1)    # start from 1 instead of 0
for i in range(5):
    print(next(c))

Or using islice():

for n in islice(count(1), 5):
    print(n)
mhawke
  • 84,695
  • 9
  • 117
  • 138