Flatten Nested List in Python

Flatten a shallow nested list (list of lists) into a single list.

IntermediateList ProgramsExample 17 of 25
flatten-nested-list.py
1# Program to flatten a nested list (one level)
2
3items = eval(input("Enter a nested list (e.g., [[1, 2], [3, 4]]): "))
4
5flattened = [elem for sublist in items for elem in sublist]
6
7print("Flattened list:", flattened)

Output

Enter a nested list (e.g., [[1, 2], [3, 4]]): [[1, 2], [3, 4]]
Flattened list: [1, 2, 3, 4]

What's going on

We use a nested list comprehension to iterate over sublists and their elements.

After this program

If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.