Flatten a 2D List

Medium ⏱ 12 min 56% acceptance ★★★★★ 4.5
Write flatten_grid(grid) that takes a list of lists (a 2D grid where rows can have different lengths) and returns a single flat list containing every element in row-major order (row 0 fully, then row 1, and so on).

Examples

Example 1
Input
grid = [[1, 2], [3], [4, 5, 6]]
Output
[1, 2, 3, 4, 5, 6]
Explanation

Elements are read row by row, left to right.

Constraints

  • 0 <= number of rows <= 1000
  • Rows may vary in length.

Topics

ListsNested Lists

Companies

AmazonGoogle

Hints

Hint 1

A nested loop appending each element works.

Hint 2

A list comprehension with two `for` clauses can also flatten it: [x for row in grid for x in row].

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.