Problem 203256 · easy · Level 02 Linear Data Structures

Flatten One Level

arrays · nested lists · type checks

Given a list items whose elements are either plain values or lists, return a new list in which every inner list is replaced by its elements, spliced in at the same position. Plain values are kept as they are. Only one level is flattened: a list nested inside an inner list stays a list.

Examples

Input:  items = [1, [2, 3], [], 4, [[5], 6]]
Output: [1, 2, 3, 4, [5], 6]
Explanation: [2, 3] and [[5], 6] are opened up; the inner [5] stays a list.

Input:  items = [[], []]
Output: []

Constraints

  • 0 <= len(items) <= 10**5, total number of values <= 10**5
  • Return a new list; do not modify items or its inner lists.
  • Target: O(total number of values) time.

Goals

  • Distinguish list items from scalar items with isinstance
  • Splice inner lists into the output with extend
  • Flatten exactly one level, no deeper
Starting Python…