Flatten a nested list, Turn a nested list like [[1, 2], [3, 4]] into [1, 2, 3, 4].
174
23-Apr-2025
Updated on 23-Apr-2025
Anubhav Kumar
23-Apr-2025Problem Statement
Here are given a list that contains other lists inside it (one level deep). Our goal is to combine all elements into a single flat list.
Approach
There are several ways to flatten a list in Python, especially for one-level deep nested lists. Here are two common approaches:
Method 1: Using List Comprehension (Recommended)
Explanation:
for sublist in nested_list: Loops through each sublist, e.g.,[1, 2]and[3, 4].for item in sublist: Loops through each item inside that sublist.item for sublist in nested_list for item in sublist: This is a nested loop inside the list comprehension.Output:
Method 2: Using
itertools.chainExplanation:
itertools.chain.from_iterable()takes an iterable of iterables and flattens it.list().Output:
Use Case
This is useful when you are dealing with 2D data structures such as a grid, spreadsheet or nested data and you want a simple, one-dimensional idea.
Read More -