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.
def counting():
i = 0
while i <= 5:
yield i
i += 1
for i in counting():
print(i)
if you run it, you get:
>>>
0
1
2
3
4
5
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.
def counting():
i = 0
while i <= 5:
yield i
i += 1
lista = list(counting())
print(lista)
if you run it, you get
>>>
[0, 1, 2, 3, 4, 5]
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 ⇒