Flatten Nested List

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

IntermediateTopic: List Programs
Back

Python Flatten Nested List Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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]

Understanding Flatten Nested List

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents