List Flatten in Python

Level 3111 keystrokes

This flattens a nested list using list comprehension. The double for loop iterates through sublists and their items.

Python code

# A list of three sublists
1nested = [[1, 2], [3, 4], [5, 6]]
# The for clauses run left to right, like nested loops: for each sublist, for each item
# Every item goes into one flat list
2flattened = [item for sublist in nested for item in sublist]
# Prints [1, 2, 3, 4, 5, 6]
3print(flattened)

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