Generation behavior in built-ins
Generator-like behavior is quite common among the built-in types and functions. This is a major difference between Python 2 and Python 3. In Python 2, functions such as map()
, zip()
, and filter()
returned lists instead of iterable objects. The idea behind this change is that if you need to make a list of those results, you can always wrap the call in a list()
class. On the other hand, if you just need to iterate and want to keep the impact on memory as light as possible, you can use those functions safely. Another notable example is the range()
function. In Python 2, it returned a list, and there was another function called xrange()
that behaved like the range()
function now behaves in Python 3.
The idea of functions and methods that return iterable objects is quite widespread. You can find it in the open()
function, which is used to operate on file objects (we will see it in Chapter 8, Files and Data Persistence), but also in enumerate()
, in the...