Structuring flat sequences

Sometimes, we'll have raw data that is a flat list of values that we'd like to bunch up into subgroups. This is a bit more complex. We can use the itertools module's groupby() function to implement this. This will have to wait until Chapter 8, The Iterools Module.

Let's say we have a simple flat list, as follows:

flat= ['2', '3', '5', '7', '11', '13', '17', '19', '23', '29',  '31', '37', '41', '43', '47', '53', '59', '61', '67', '71',  ... ]

We can write nested generator functions to build a sequence-of-sequence structure from flat data. To do this, we'll need a single iterator that we can use multiple times. The expression looks like the following code snippet:

>>> flat_iter = iter(flat) >>> (tuple(next(flat_iter) ...

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.