Merging sequences with zip

The last built-in we'll look at is zip(), which, as its name suggests, gives us a way to synchronise iterations over two iterable series. For example, let's zip together two columns of temperature data, one from Sunday and one from Monday:

>>> sunday = [12, 14, 15, 15, 17, 21, 22, 22, 23, 22, 20, 18]
>>> monday = [13, 14, 14, 14, 16, 20, 21, 22, 22, 21, 19, 17]
>>> for item in zip(sunday, monday):
... print(item)
...
(12, 13)
(14, 14)
(15, 14)
(15, 14)
(17, 16)
(21, 20)
(22, 21)
(22, 22)
(23, 22)
(22, 21)
(20, 19)
(18, 17)

We can see that zip() yields tuples when iterated. This in turn means we can use it with tuple unpacking in the for-loop to calculate the average temperature for each hour on these days:

>>> for sun, mon in zip(sunday, monday):
... print("average =", (sun + mon) / 2)
...
average = 12.5
average = 14.0
average = 14.5
average = 14.5
average = 16.5
average = 20.5
average = 21.5
average = 22.0
average = 22.5
average = 21.5
average = 19.5
average = 17.5
..................Content has been hidden....................

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