The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
nested_list = [[1, 2], [3, 4]]
# Flattening the list using list comprehension
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)
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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Problem 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 -