Home >Backend Development >Python Tutorial >How Can I Efficiently Flatten a Nested List in Python?
Problem Statement:
You are given a nested list and need to flatten it into a single list. For instance, you have a list of lists like:
[[1, 2, 3], [4, 5, 6], [7], [8, 9]]
The goal is to flatten this structure into a single list:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Solution:
To flatten a list of lists, you can utilize a nested list comprehension. This technique involves iterating through each inner list (represented by xs in the code) and appending each individual element (represented by x) to a flattened list (named flat_list):
flat_list = [ x for xs in xss for x in xs ]
This is equivalent to the following explicit iteration using nested loops:
flat_list = [] for xs in xss: for x in xs: flat_list.append(x)
Alternatively, you can create a function to perform this flattening operation:
def flatten(xss): return [x for xs in xss for x in xs]
Using this function, you can flatten the input list as follows:
flat_list = flatten([[1, 2, 3], [4, 5, 6], [7], [8, 9]])
This approach is highly efficient and performs significantly better than other methods such as using or reduce. The list comprehension technique ensures that each element is copied only once to the flattened list.
The above is the detailed content of How Can I Efficiently Flatten a Nested List in Python?. For more information, please follow other related articles on the PHP Chinese website!