Flattening One Level of a Nested Sequence

One-level flattening concatenates the child sequences in traversal order and leaves values deeper in the structure as values.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Make the loops explicit
  2. Check the depth policy
  3. Write the desired output order before coding
  4. Count work by what appears in each row

Make the loops explicit

For [[1, 3], [], [2]], visit the child lists in order and output 1, 3, and 2. The empty list yields no item. This traversal is a specific use of nested loops, with the inner sequence varying at every step.

Check the depth policy

For [[[1]], [[2]]], flattening one level yields [[1], [2]]. Recursively flattening every level would yield [1, 2]. A contract should say which structure the caller expects to preserve.[1]

Write the desired output order before coding

Consider rows [[3, 1], [], [8, 6, 4]]. Visiting each row in input order and each element in row order produces [3, 1, 8, 6, 4]. An empty row contributes zero elements, so its position can no longer be inferred from the flattened list. If downstream code needs that information, include coordinate pairs such as (2, 0, 8) or preserve row lengths alongside the values. Write down whether flattening removes a single layer or all nested layers. Applied once to [[[3]], [[8, 6]]], it should leave [[3], [8, 6]]. See nested-loop traversal for the order.

Count work by what appears in each row

For \(r\) rows of lengths \(\ell_1,\ldots,\ell_r\), an ordinary nested loop visits the rows and copies \(\sum_i\ell_i\) elements. A table of one million empty rows still requires visiting one million containers, even though no values are produced. Returning a generator keeps the intermediate output small when consumers can process values as they arrive. A consumer that needs random access must eventually materialize the values or choose a different representation. Test both ragged rows and leading empty rows. Mathematically rectangular examples can hide a loop that incorrectly uses the length of the first row for every row.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩