An implementation of an infinite list of elements in Python

  • 2020-04-02 13:54:04
  • OfStack

This article is an example of how Python can implement an infinite list of elements using Yield.

The following two example pieces of code implement a simple infinite list of elements through the Python Yield generator.

Increment an infinite list

The specific code is as follows:


def increment():
 i = 0
 while True:
  yield i
  i += 1
 
for j in increment():
 print i
 if (j > 10) : break

2. Fibonacci infinite list

The specific code is as follows:


def fibonacci():
 i = j = 1
 while True:
  result, i, j = i, j, i + j
  yield result
 
for k in fibonacci():
 print k
 if (k > 100) : break

Related articles: