I would like to know what it means to flatten e.g. flatten an iterator of iterators. Can you tell me? Are there any C/Java/Python idioms for it?
2 Answers
In this context, to flatten means to remove nesting. For instance, an array of arrays (an array where each element is an array) of integers is nested; if we flatten it we get an array of integers which contains the same values in the same order, but next to each other in a single array, rather than split into several arrays: [[1 2] [3 4]] -> [1 2 3 4]
. Same difference with iterators, other collections, and deeper nesting (array of array of sets of iterators of strings).
As for idioms, there aren't really many -- it's not a common task, and often simple. Note that in the case of regular arrays (all nested arrays are of the same size), nested[i][j]
is equivalent to nested[i * INNER_ARRAY_SIZE + j]
. This is sometimes used to avoid nesting, especially in languages which treat arrays as reference types and thus require many separately-allocated arrays if you nest them. In Python, you can flatten iterables with itertools.chain(*iterable_of_iterables)
.
-
1-1 The standard python idiom for flattening iterables is to use `itertools.chain`. – Marcin Aug 26 '12 at 16:01
Flattening means to remove nesting of sequence types. Python provides itertools.chain(*iterables)
for this purpose (http://docs.python.org/library/itertools.html#itertools.chain).

- 48,559
- 18
- 128
- 201