Home >Backend Development >Python Tutorial >What's the Most Efficient Way to Flatten a List of Lists in Python?

What's the Most Efficient Way to Flatten a List of Lists in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-23 14:01:14492browse

What's the Most Efficient Way to Flatten a List of Lists in Python?

Flattening Lists of Lists

Flattening a list of lists involves converting a nested structure into a single-level list. In Python, this can be achieved using several methods.

Nested List Comprehension

The most efficient method is a nested list comprehension:

flat_list = [x for xs in xss for x in xs]

This expression iterates over each inner list and appends each element to the resulting flat list.

Using the Operator

You can also flatten lists using the operator:

flat_list = []
for xs in xss:
    flat_list = flat_list + xs

This method is marginally slower than the list comprehension due to repeated list concatenation.

Using sum with an Empty List

Another approach uses the sum function with an empty list:

flat_list = sum(xss, [])

This method is less efficient than the list comprehension, especially for large lists.

Using functools.reduce

Finally, you can use the functools.reduce function:

from functools import reduce
flat_list = reduce(lambda xs, ys: xs + ys, xss)

Again, this method is slower than the list comprehension.

Performance tests using the timeit module show that the list comprehension is the fastest method.

The above is the detailed content of What's the Most Efficient Way to Flatten a List of Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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