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 browser1# Program to flatten a nested list (one level)23items = eval(input("Enter a nested list (e.g., [[1, 2], [3, 4]]): "))45flattened = [elem for sublist in items for elem in sublist]67print("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.