Home > Backend Development > Python Tutorial > How Can I Efficiently Flatten a Nested List in Python?

How Can I Efficiently Flatten a Nested List in Python?

Susan Sarandon
Release: 2024-12-31 03:09:10
Original
479 people have browsed it

How Can I Efficiently Flatten a Nested List in Python?

Flattening a List of Lists

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]]
Copy after login

The goal is to flatten this structure into a single list:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy after login

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
]
Copy after login

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)
Copy after login

Alternatively, you can create a function to perform this flattening operation:

def flatten(xss):
    return [x for xs in xss for x in xs]
Copy after login

Using this function, you can flatten the input list as follows:

flat_list = flatten([[1, 2, 3],
                   [4, 5, 6],
                   [7],
                   [8, 9]])
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template