Flatten A List Of Lists In Python

Summary: Flattening a list means converting a nested list into a simple single-dimensional list. To flatten a nested list we can use the for loop or the While loop or recursion or the deepflatten() Method. Other techniques include importing numerous external Python libraries and using their built-in functions.

Overview

Problem: Given a list of lists in Python; how to flatten the list?

Now, some of you might be thinking what does flattening a list actually mean? 🤔

Answer:

Flattening a list is the process used to convert a multidimensional or nested list (list of lists) into a one-dimensional list. Let’s have a look at an example to get a clearer picture of flattening a list.

Example: Consider the given list as shown below.

[[10,20],[30,40,50]]

After flattening the list it looks something like this:

[10,20,30,40,50]

Types Of List Flattening

Shallow Flattening is the process of flattening lists that only have a depth of one-level.

Example: Consider the list as given below (it represents a list that one-level depth)

li = [[100,200],[300,400]]

Flattened (Shallow) List:

[100,200,300,400,500]

Deep Flattening is the process of flattening lists that have varying depths.

Example: Consider the given list given below (it represents a list of varying depth).

l = [ [100,150], [ [200 ] ], [ 300, 400 ] ]

Flattened (Deep) List:

[100,150,200,300,400]

Now that we know what flattening means and its types, let us understand how we can flatten lists. Without further delay, let the games begin!

Method 1: Using For Loop

A simple approach to shallow flattening is to use a nested for loop and append the values of the nested list one by one. Let’s have a look at how this can done in a program.

li = [[10,20],[30,40]]
flat_li = []
for i in li:
  for item in i:
    flat_li.append(item)
print("list before flattening", li)
print ("flattened list: ",flat_li)

Output:

list before flattening [[10, 20], [30, 40]]
flattened list: [10, 20, 30, 40]

Method 2: Using A List Comprehension

The above method can be packed in a single line using a list comprehension. This is a very concise and efficient way of flattening lists in Python.

List comprehension is a compact way of creating lists. The simple formula is [expression + context]. For a more detailed explanation, please follow our blog tutorial here.

The following program uses a list comprehension to derive a one-line solution to flatten lists in Python.

li = [[10,20],[30,40]]
print("list before flattening", li)
print ("list after flattening",[item for i in li for item in i])

Output

list before flattening [[10, 20], [30, 40]]
list after flattening [10, 20, 30, 40]

Method 3: Using itertools.chain()

chain() is a method within the itertools module that accepts a series of iterable and then returns a single iterable. The generated output which is a single iterable cannot be used directly and has to be explicitly converted. This method allows us to avoid creating extra lists.

To flatten a list of lists we can use the itertools.chain() method and unpack the given list using the * operator.

Example:

import itertools
li = [ [100,150], [ [200 ] ], [ 300, 400 ] ]
print("list before flattening", li)
flat_li = list(itertools.chain(*li))
print("list after flattening", flat_li)

Output:

list before flattening [[100, 150], [[200]], [300, 400]]
list after flattening [100, 150, [200], 300, 400]

Note: In case you do not want to use the * operator for unpacking the list, you can use the itertools.chain.from_iterable()

import itertools
li = [ [100,150], [ [200 ] ], [ 300, 400 ] ]
print("list li before flattening", li)
flat_li = list((itertools.chain.from_iterable(li)))
print("list li after flattening", flat_li)

Output:

list li before flattening [[100, 150], [[200]], [300, 400]]
list li after flattening [100, 150, 200, 300, 400]

Method 4: Using flatten() Method

We can flatten lists using the flatten() function of the iteration_utilities module.

Syntax:

iteration_utilities.flatten(iterable)

Example:

from iteration_utilities import flatten
li = [[100, 150], [[200]], [300, 400]]
print(list(flatten(li)))

Output:

[100, 150, [200], 300, 400]

This solves our purpose only to an extent because flatten() operates at one level of list nesting. However, we want a solution that looks something like this:- [100, 150, 200, 300, 400]. This means we need a complete deep flattening of the given list which brings us to deep flattening of lists.

Method 5: Using deepflatten() Method

In order to achieve deep flattening of nested lists, we need the assistance of a built-in module known as deepflatten which is a part of the iteration_utilities library.

Note: Since iteration_utilities is not a part of the Python standard library, you have to explicitly install it using the following command:

pip install iteration-utilities

Let us have a look at the following program to understand how the deepflatten module, moves into multiple level of depths and then flattens the given list.

from iteration_utilities import deepflatten
li = [ [100,150], [ [200 ] ], [ 300, 400 ] ]
print("list li before flattening", li)
flat_li = list(deepflatten(li))
print("list li after flattening", flat_li)
print("\n")
deep_li = [[0,1], [[2, [3, [4, [5, [6 ]]]]]], [7,8]]
print("list deep_li before flattening", li)
flat_li = list(deepflatten(li))
print("list deep_li after flattening", flat_li)

Output:

list li before flattening [[100, 150], [[200]], [300, 400]]
list li after flattening [100, 150, 200, 300, 400]

list deep_li before flattening [[100, 150], [[200]], [300, 400]]
list deep_li after flattening [100, 150, 200, 300, 400]

The above example clearly depicts, how efficient the deepflatten method is. I mentioned couple of lists with different depths purposely, so that you can have an idea about the utility of the deepflatten function. You don’t even need any other function or module if you are using the deepflatten() function. It is self sufficient and can flatten the given list by itself.

Method 6: Using While Loop

Another approach to flatten the given list is to use a while loop to pop all the elements out of the given list based on the type of element and then append it to the new flattened list. Let us have a look at the code given below to understand how this works.

def flatten(l): 
    li = []
    while l: #iterate until provided list is empty.
            e = l.pop()
            if type(e) == list: #check type of the poped item.
                    l.extend(e) #if popped item is list then extend the item to given list.
            else:
                    li.append(e) #if popped item is not list then add it to li
    li.sort()
    return li


a = [[100, 150], [[200]], [300, 400]]
print("list before flattening: ", a)
print("list after flattening: ", flatten(a))

Output:

list before flattening:  [[100, 150], [[200]], [300, 400]]
list after flattening:  [100, 150, 200, 300, 400]

Method 7: Using Recursion

If you are ok with recursion then you might want to have a look at how to flatten lists using recursion. The advantage of this method is, it does not need any other imports.

Let us have a look at the following example to understand hw we can use recursion to flatten nested lists.

li = [[100, 150], [[200]], [300, 400]]

def flatten(l):
    if len(l) == 1:
            if type(l[0]) == list:
                    result = flatten(l[0])   
            else:
                    result = l
    elif type(l[0]) == list:
            result = flatten(l[0]) + flatten(l[1:])
    else:
            result = [l[0]] + flatten(l[1:])
    return result

print(flatten(li))

Output:

[100, 150, 200, 300, 400]

📚 Flattening Lists Using Python Libraries

We can leverage the power of different Python libraries and use the in-built methods within them to flatten lists in Python. Let us go quickly through some of these in this article.

Pandas

from pandas.core.common import flatten

li = [[100, 150], [200], [300, 400]]

print("list before flattening: ", li)
print("list after flattening: ", list(flatten(li)))

Matplotlib

from matplotlib.cbook import flatten

li = [[100, 150], [200], [300, 400]]

print("list before flattening: ", li)
print("list after flattening: ", list(flatten(li)))

Unipath

import unipath
from unipath.path import flatten

li = [[100, 150], [200], [300, 400]]

print("list before flattening: ", li)
print("list after flattening: ", list(flatten(li)))

Setuptools

from setuptools.namespaces import flatten

li = [[100, 150], [200], [300, 400]]

print("list before flattening: ", li)
print("list after flattening: ", list(flatten(li)))

Functools

import functools
import operator

li = [[100, 150], [200], [300, 400]]

print("list before flattening: ", li)
print("list after flattening: ",(functools.reduce(operator.concat, li)))

Output:

The output in case of all the above codes will be as given below.

list before flattening:  [[100, 150], [[200]], [300, 400]]
list after flattening:  [100, 150, [200], 300, 400]

Conclusion

We learned the following in this article:

  • What is list flattening and types of list flattening?
  • Using for loop to flatten the list.
  • Using a list comprehension to flatten the list.
  • Using itertools.chain() to flatten the list.
  • Using the flatten method to flatten the list.
  • Using the deepflatten() method to flatten the list.
  • Using a While loop to flatten the list.
  • Using Recursion to flatten the list.
  • Flattening lists using Python libraries:
    • Pandas
    • Matpotlib
    • Unipath
    • Setuptools
    • Functools

I hope you can easily flatten lists using the methods discussed in this article. Please subscribe and stay tuned for more interesting articles.

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!