Python Lessons – 6.4 Generators

Python Lesson - 6.4 Generators

Generators

Generators are a type of iterable, like lists and tuples. But unlike lists, generators do not allow indexing with arbitrary indices, but can still be iterated through for loops.

To define these generators, the yield clause is used, replacing the return within a function.

if you run it, you get:

While the lists have problems with memory restrictions, the generators do not have it at all and can be infinite.

In summary, the generators allow you to declare a function that behaves like an iterator, then using it in a for loop.

Furthermore, it is possible to convert generators into lists by passing them as an argument to the list () function.

if you run it, you get

The use of generators greatly increases the performance of the code, greatly reducing the memory usage of the program. Since it is not any generation of values, assignment and wait for the time that these operations are carried out by the processor.

⇐ Go to Python Lesson 6.3 – Map and Filter

Go to Python Lesson 6.5 – Decorators ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.