Flatten Nested List

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

PythonIntermediate
Python
# Program to flatten a nested list (one level)

items = eval(input("Enter a nested list (e.g., [[1, 2], [3, 4]]): "))

flattened = [elem for sublist in items for elem in sublist]

print("Flattened list:", flattened)

Output

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

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