April 2018
Intermediate to advanced
408 pages
10h 42m
English
In Chapter 4, Working with Collections, we looked at slice notation to select subsets from a collection. Our example was to pair up items sliced from a list object. The following is a simple list:
flat= ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71',... ]
We can create pairs using list slices as follows:
>>> list(zip(flat[0::2], flat[1::2]))[(2, 3), (5, 7), (11, 13), ...]
The islice() function gives us similar capabilities without the overhead of materializing a list object. This will work with an iterable of any size. It looks like the following:
flat_iter_1= iter(flat) flat_iter_2= iter(flat) zip( islice(flat_iter_1, 0, None, 2), islice(flat_iter_2, ...