Python list comprehension flatten list of lists

In this tutorial, we’ll look at how to flatten a list of lists in Python to a single list through some examples. Suppose you have a list of lists –

[['a','b','c'],['d','e','f'],['g','h','i']]

Which you want to flatten out to a single list –

['a','b','c','d','e','f','g','h','i']

How to flatten a list of lists?

There are a number of ways to flatten a list of lists in python. You can use a list comprehension, the itertools library, or simply loop through the list of lists adding each item to a separate list, etc. Let’s see them in action through examples followed by a runtime assessment of each.

1. Naive method – Iterate over the list of lists

Here, we iterate through each item of all the subsequent lists in a nested loop and append them to a separate list.

# flatten list of lists ls = [['a','b','c'],['d','e','f'],['g','h','i']] # iterate through list of lists in a nested loop flat_ls = [] for i in ls: for j in i: flat_ls.append[j] # print print["Original list:", ls] print["Flattened list:", flat_ls]

Output:

Original list: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Flattened list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

In the above example, the outer loop iterates over all the subsequent lists while the inner loop iterates over the items in each of the subsequent lists with each item being appended to the list flat_ls.

2. Using list comprehension

You can also use a list comprehension to basically do the same thing as in the previous step but with better readability and faster execution.

# flatten list of lists ls = [['a','b','c'],['d','e','f'],['g','h','i']] # using list comprehension flat_ls = [item for sublist in ls for item in sublist] # print print["Original list:", ls] print["Flattened list:", flat_ls]

Output:

Original list: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Flattened list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

Here, we use list comprehension to create a flattened list by keeping each item of each of the sublists in the original list of lists. Using list comprehension is similar to nested looping but has better readability [in this use case] and is faster [which we’ll see later in the article].

3. Using the itertools library

The python itertools standard library offers handy functionalities for working with iterables. Here, we break the list of lists into individual parts and then chain them together into a single iterable.

import itertools # flatten list of lists ls = [['a','b','c'],['d','e','f'],['g','h','i']] # using itertools flat_ls = list[itertools.chain[*ls]] # print print["Original list:", ls] print["Flattened list:", flat_ls]

Output:

Original list: [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] Flattened list: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

In the above example itertools.chain[] function is used to join [or chain together] the iterables passed as parameters. Passing *ls to it results in the outer list to be unpacked as parameters which are then chained together. The following example illustrates this better.

ls1 = list[itertools.chain[[1,2,3],[4,5],[6]]] ls2 = list[itertools.chain[*[[1,2,3],[4,5],[6]]]] print[ls1] print[ls2]

Output:

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

You can see that for ls1 we pass the iterables that we want to chain together as parameters to the itertools.chain[] function. For ls2, since we’re passing a single list of lists, we need to unpack it to its component iterables using *.

Alternatively, if you’re not comfortable with using *, you can use the itertools.chain.from_iterable[] function which doesn’t require you to unpack your list.

ls3 = list[itertools.chain.from_iterable[[[1,2,3],[4,5],[6]]]] print[ls3]

Output:

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

Comparing the methods for runtime

Now let’s compare the different methods discussed above to flatten a list of lists for runtime.

%%timeit ls = [['a','b','c'],['d','e','f'],['g','h','i']] flat_ls = [] for i in ls: for j in i: flat_ls.append[j] 1.45 µs ± 104 ns per loop [mean ± std. dev. of 7 runs, 1000000 loops each] %%timeit ls = [['a','b','c'],['d','e','f'],['g','h','i']] flat_ls = [item for sublist in ls for item in sublist] 1.12 µs ± 128 ns per loop [mean ± std. dev. of 7 runs, 1000000 loops each] %%timeit ls = [['a','b','c'],['d','e','f'],['g','h','i']] flat_ls = list[itertools.chain[*ls]] 875 ns ± 20.2 ns per loop [mean ± std. dev. of 7 runs, 1000000 loops each]

Of the three methods discussed, we found using itertools.chain[] to be the fastest and using a direct nested loop to be the slowest. List comprehensions are not only fast but can be intuitive and readable for such cases [where they’re short and simple].

With this, we come to the end of this tutorial. We discussed some of the common ways of flattening a list of lists in python along with their examples and runtime performances. There are, however, other methods as well. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python [version 3.8.3] kernel.


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Converting a 2D array into a 1D array is called flattening. There are many approaches to solve the problem.

We will explore some of them in this tutorial.

Let’s see an example.

Input

[[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]]

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

#1. Loops

The most common way to solve the problem is by using loops. I think most of you already got it. Let’s see the steps to solve the problem using loops.

  • Initialize the list of lists with dummy data and name it as data.
  • Now, initialize an empty list called flat_list.
  • Iterate over the data.
    • Unpack all the elements from the current list.
    • Add them to the flat_list using the list append method.
  • Print the result.

See the code for the problem below.

# initializing the data and an empty list data = [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]] flat_list = [] # iterating over the data for item in data: # appending elements to the flat_list flat_list += item # printing the resultantn flat_list print[flat_list]

You can use another loop to add sub-list elements to flat_list instead of a concatenation operator. We can also use list comprehensions instead of loops.

Both do the same work. Let’s see the next way to solve the problem.

#2. Itertools – Chain

We will use a method called chain from itertools built-in module.

The method chain iterates over each sub-list and returns the elements until there are no sub-lists in it. It returns an iterable that we have to convert it into a list.

Let’s see the steps involved in solving the problem.

  • Initialize the list of lists with dummy data and name it as data.
  • Get the flatten iterable using itertools.chain[*data].
  • Conver the resultant iterable into a list.
  • Print the flatten list.

You can go through the code in the below snippet.

# importing the module import itertools # initializing the data data = [[1, 2, 3], [4, 5], [6, 7, 8, 9, 10]] # flattening the list and storing the result flat_list = itertools.chain[*data] # converting iterable to list and printing print[list[flat_list]]

#3. Flatten Multi-Level Lists

We have seen how to flatten a list of lists. The above methods that we have discussed to flatten the list won’t work for multi-level lists. Let’s see an example.

Input

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

Output

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

As we don’t know the depth of the lists before the program, we have to use recursion to solve the problem.

  • Initialize the data as shown in the example and name it as data.
  • Initialize an empty list called flat_list.
  • Write a function called flatten_list.
    • Iterate over the elements of the given list.
    • If the element is a list then recursively call the same function again.
    • If the element is not a list, then append the element to the flat_list.
  • Invoke the function with data.
  • The function will fill all the elements in the flat_list list.
  • Print the flat_list to check the output.

Phew! a lot of steps to code. Don’t worry. Converting the above statements into code won’t take more than mins.

# initializing the data and empty list data = [1, [2, 3, [4, 5]], 6, [[7], [8, 9]]] flat_list = [] # function def flatten_list[data]: # iterating over the data for element in data: # checking for list if type[element] == list: # calling the same function with current element as new argument flatten_list[element] else: flat_list.append[element] # flattening the given list flatten_list[data] # printing the flat_list print[flat_list]

Remember, we didn’t convert the existing list. Instead, we have created a new list with the given list element.

Conclusion

Hope you have enjoyed the tutorial. There might be many other ways to flatten a list in Python but I felt the above are probably the easiest ones.

Happy Coding 🙂

Video liên quan

Chủ Đề