5 Best Ways to Flatten a Python List of Lists into One List

πŸ’‘ Problem Formulation: In many programming scenarios, developers encounter a data structure known as a “list of lists,” where each element is itself a list. The challenge arises when we need to flatten this structure into a single list, merging all sublists into one. For instance, converting [[1, 2], [3, 4], [5, 6]] into [1, 2, 3, 4, 5, 6]. This article explores various methods to achieve such flattening in Python.

Method 1: Looping Through Sublists

A straightforward method to flatten a list of lists is to iterate through each sublist and extend a new list with the elements of these sublists. The extend() method is used which iterates over its argument, adding each element to the list, extending the list.

Here’s an example:

flat_list = []
list_of_lists = [[1, 2], [3, 4], [5, 6]]

for sublist in list_of_lists:
    flat_list.extend(sublist)

Output:

[1, 2, 3, 4, 5, 6]

This code snippet creates an empty list named flat_list. It then loops through each sublist in the list_of_lists and uses extend() method to add elements of these sublists into flat_list. By the end of the loop, flat_list contains all elements from the sublists sequentially.

Method 2: Using List Comprehension

List comprehension is a concise way to create lists in Python. This method makes use of a single line of code to iterate through each element of the sublists and collect them into a new flattened list. It is a more pythonic and often faster alternative to traditional for loops.

Here’s an example:

list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = [item for sublist in list_of_lists for item in sublist]

Output:

[1, 2, 3, 4, 5, 6]

The code snippet uses list comprehension to iterate over each sublist and then over each item within those sublists. Each item is added to the flat_list in the order they appear. This method is both elegant and efficient.

Method 3: Using itertools.chain()

The itertools.chain() function from the itertools module is a powerful tool in Python for iterating over several iterables in sequence. This allows us to effectively flatten a list of lists by chaining them together into one continuous iterable, which we then convert into a list.

Here’s an example:

from itertools import chain
list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = list(chain(*list_of_lists))

Output:

[1, 2, 3, 4, 5, 6]

In this code snippet, we first import chain from the itertools module. *list_of_lists unpacks our list of lists so that chain() can iterate over all sublists as if they were a single iterable. The result is then cast to a list to produce our flattened list.

Method 4: Using the sum() Function

The sum() function, traditionally used for adding numbers, can be repurposed to concatenate lists by specifying the start value as an empty list. This method starts with an empty list and successively adds all sublists to it, similar to a reduce operation.

Here’s an example:

list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = sum(list_of_lists, [])

Output:

[1, 2, 3, 4, 5, 6]

Here, sum() takes two arguments: the list_of_lists and the starting value, which is an empty list []. It effectively concatenates all sublists in list_of_lists into a single flattened list stored in flat_list.

Bonus One-Liner Method 5: Using functools.reduce()

A functional programming tool, functools.reduce(), can be used to apply a function cumulatively to the items of an iterable, from left to right. This can be leveraged to flatten a list by concatenating its sublists.

Here’s an example:

from functools import reduce
list_of_lists = [[1, 2], [3, 4], [5, 6]]
flat_list = reduce(lambda a, b: a + b, list_of_lists)

Output:

[1, 2, 3, 4, 5, 6]

The reduce() function takes two parameters: a function and an iterable. The lambda function lambda a, b: a + b specifies how the elements should be combined, in this case by concatenating them. This pattern is applied across the list_of_lists to produce a flat list.

Summary/Discussion

  • Method 1: Looping. Straightforward and understandable. Might not be the most elegant or efficient for large lists.
  • Method 2: List Comprehension. Concise and memory efficient. Highly recommended for its Pythonic approach.
  • Method 3: itertools.chain(). Designed for chaining iterables, more efficient than looping for large datasets. Requires an extra import statement.
  • Method 4: sum() Function. A creative use of sum, but can be slower and less intuitive for code maintenance.
  • Method 5: functools.reduce(). Functional programming approach, can be less readable for those unfamiliar with the function. Potentially efficient for large lists.