Structuring flat sequences – an alternative approach

Let's say we have a simple, flat list and we want to create pairs from this list. The following is the required data:

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:

zip(flat[0::2], flat[1::2])

The slice flat[0::2] is all of the even positions. The slice flat[1::2] is all of the odd positions. If we zip these together, we get a two-tuple. The item at index  [0] is the value from the first even position, and then the item at index [1] is the value from the first odd position. If the number of elements is even, this will produce pairs nicely. If the total number ...

Get Functional Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.