Nested List in Python

Level 387 keystrokes

This flattens a nested list using list comprehension. The nested for loops extract each element from the 2D structure.

Python code

# Create a 2D list (matrix) with 3 rows
1matrix = [[1, 2], [3, 4], [5, 6]]
# Nested list comprehension to flatten
# First loop iterates over rows, second over elements in each row
2flat = [n for row in matrix for n in row]
# Print the flattened 1D list
3print(flat)

Output

[1, 2, 3, 4, 5, 6]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 5
  • [× 5
  • ]× 5
  • =× 2
  • (× 1
  • )× 1

More Python examples at level 3

← Python typing practice