Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Use a Generator to Implement an Infinite Sequence

Python Use a Generator to Implement an Infinite Sequence

Document Object Reference Manual Python3 Examples

In Python, a generator is a special kind of iterator that allows you to generate values on demand rather than generating all of them at once. Generators are well suited for handling infinite sequences because they only generate values when needed, saving memory.

The following is an example of using a generator to implement an infinite sequence that starts from 0 and increments by 1 each time.

Example

def

infinite_sequence

(

)

:

    num

=

0

   

while

True

:

       

yield

num

        num +

=

1

Code analysis:

Output result: Since this is an infinite sequence, the generator will keep generating values. You can use the next() function to get the next value in the sequence.

gen = infinite_sequence()
print(next(gen))  # 输出: 0
print(next(gen))  # 输出: 1
print(next(gen))  # 输出: 2
# For example...

Each time you call next(gen) , the generator resumes execution from where it last paused and returns the next value.

Document Object Reference Manual Python3 Examples