Iterators and Generators
In Python, an iterator (Iterator) is a way to iterate through a collection of data, and you can access the elements in the collection one by one without loading the entire collection into memory in advance. Iterators in Python are usually implemented based on iterable objects (Iterable), such as lists, tuples, dictionaries, strings, etc.
A generator (Generator) is a special iterator that can dynamically generate data in each loop instead of generating all data at once. Generators are great for dealing with large amounts of data because they only compute and generate what is needed when necessary, rather than generating all the data at once, which is memory-intensive.
The difference between them is that an iterator is implemented by defining a class, __iter__()
and __next__()
two methods of and must be implemented. The meaning, usage, and return value of each method need to consider all details when implementing it. The generator is relatively simple, you can use the keyword yield
to generate data, and each time the generator is called, it will automatically yield
continue to execute from the previous statement until the generator ends or return
the statement . In Python, generators are usually defined by functions, for example:
def my_generator(num):
for i in range(num):
yield i
This generator function is used to 0
generate num - 1
integers from to , and the elements in the generator can be accessed through for
a loop , for example:
for item in my_generator(10):
print(item)
Here my_generator(10)
returns a generator object that dynamically generates integers from0
to , looping until the generator ends or a statement is encountered.9
return