Why would python3 change the filter () return value to an iterator object? What are the benefits?

Why would python3 change the return value of filter () to an iterator object? What are the benefits of
?
it"s not very troublesome to deal with, but I just don"t understand the reason why Python3 is changed like this

Feb.22,2022

simple reason: memory saving. Functions such as map and filter return an iterator that has the characteristics of a class generator. We know that the generator is lazily loaded, and it only calculates the values generated this time the next time it is called, instead of generating all the values in advance as the list does and then returning the next value in the list with each call. This approach requires all values to be saved in advance in the list, which is very memory-consuming when the list is large.
consider a scenario where there is a 2GB-sized text document with tens of millions of user records, and now you need to use filter to find all the records whose usernames begin with abc and write them to another text document. If filter returned a list of all the matching user records instead of an iterator, the memory consumption of storing this user information would be amazing and unacceptable. Because filter returns an iterator, we can read and process user records one by one from such a text document with very little memory cost.


because the iterable object processed by map/filter itself may be a generator.

if you return a list, it will bring them a lot of restrictions. In
2.x, I cannot return an iterator through map and filter. I can only read all the data into memory at once. If I am reading the lines of a very large file, I can only avoid using map and filter, because memory will overflow
and now return a generator. This problem avoids
. At the same time, it is not troublesome to convert to a list. Just one more step.

Menu