Lazily concatenating sequences with chain()

Perhaps, though, we'd like one long temperature series for Sunday, Monday and Tuesday. Rather than creating a new list by eagerly combining the three lists of temperatures, we can lazily concatenate iterables using itertools.chain():

>>> from itertools import chain
>>> temperatures = chain(sunday, monday, tuesday)

The temperatures  variable is an iterable object that first yields the values from sunday, followed by those from monday, and finally those from tuesday. Since it's lazy, though, it never creates a single list that contains all of the elements; in fact, it never creates an intermediate list of any sort!

We can now check that all of those temperatures are above freezing point, without the memory impact of data duplication:

>>> all(t > 0 for t in temperatures)
True
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset