6 ways to flatten Python lists

Practical Techniques for Flattening Lists in Python, from Simple Tricks to Advanced Methods

Flattening lists in Python is a handy skill, especially when dealing with nested lists. Luckily, Python gives us plenty of tools to get the job done, from list comprehension to specialized libraries.

Here, we’ll explore six easy and effective ways to flatten lists, each with its own benefits. Let’s dive in and find the best method for your project.

1. List Comprehension

List comprehension is one of the quickest ways to flatten a list in Python. It’s simple, readable, and doesn’t require any extra libraries.

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

Here, we’re looping through each sublist, then each item in that sublist, gathering all items into a single, flat list.

2. itertools.chain.from_iterable()

If you need a more efficient approach, especially with larger lists, itertools.chain.from_iterable() is a solid choice. It’s known for handling large data efficiently:

from itertools import chain
x = [[1, 2, 3], [4, 5]]
flat_list = list(chain.from_iterable(x))

Using chain.from_iterable() simplifies flattening by treating each sublist as a sequence to merge together.

3. The sum() Trick to Flatten Lists

Here’s a lesser-known trick for flattening lists: the built-in sum() function. While unconventional, it’s quick for smaller lists:

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

The sum() function takes two arguments: the iterable (our list) and a starting value, which here is []. sum() then “adds” each sublist to the starting list, resulting in a flattened list.

However, it’s worth noting that sum() can be slower than other methods for larger lists, and it only works if every item is a list.

4. numpy.flatten() for Flattening Lists

If you’re working with arrays or multi-dimensional data, numpy offers a convenient way to flatten lists, especially if they’re in an array format. This method is ideal for numerical data.

import numpy as np
x = np.array([[1, 2, 3], [4, 5]])
flat_list = x.flatten().tolist()

Using numpy.flatten() will give you a one-dimensional array, which we convert back to a standard Python list with .flatten().

5. functools.reduce()

If you prefer functional programming, functools.reduce() offers another way to flatten lists in Python. Although it’s less common, it’s useful if you’re comfortable with lambda functions.

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

With reduce(), each sublist is added to the next, creating a single flattened list in the end.

6. Using a Nested Loop to Flatten Lists

Finally, a classic nested loop is always a reliable choice. This approach requires a bit more code, but it’s flexible and doesn’t need any imports.

x = [[1, 2, 3], [4, 5]]
flat_list = []
for sublist in x:
    for item in sublist:
        flat_list.append(item)

The nested loop gives you more control, making it ideal if you need custom handling for each element in the sublists.

Choosing the Best Way to Flatten a List in Python

Each method has its strengths. For quick, readable solutions, list comprehension or itertools.chain works well.

If you’re dealing with larger or multi-dimensional data, consider using numpy.flatten().

Meanwhile, sum() offers a fun alternative but is best suited for smaller lists due to its performance limitations.

With these options, you’re ready to flatten lists efficiently in Python. Whether you’re going for simplicity or speed, there’s a solution here that’ll fit your needs.

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

Reply

or to participate.