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
Run in browser
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.