How to Flatten a List of Lists in Python
by:
blow post content copied from Real Python
click here to view original post
Flattening a list in Python involves converting a nested list structure into a single, one-dimensional list. A common approach to flatten a list of lists is to use a for
loop to iterate through each sublist. Then, add each item to a new list with the .extend()
method or the augmented concatenation operator (+=
). This will “unlist” the list, resulting in a flattened list.
Alternatively, Python’s standard library offers tools like itertools.chain()
and functools.reduce()
to achieve similar results. You can also use a list comprehension for a concise one-liner solution. Each method has its own performance characteristics, with for
loops and list comprehensions generally being more efficient.
By the end of this tutorial, you’ll understand that:
- Flattening a list involves converting nested lists into a single list.
- You can use a
for
loop and.extend()
to flatten lists in Python. - List comprehensions provide a concise syntax for list transformations.
- Standard-library functions like
itertools.chain()
andfunctools.reduce()
can also flatten lists. - The
.flatten()
method in NumPy efficiently flattens arrays for data science tasks. - Unlisting a list means to flatten nested lists into one list.
To better illustrate what it means to flatten a list, say that you have the following matrix of numeric values:
>>> matrix = [
... [9, 3, 8, 3],
... [4, 5, 2, 8],
... [6, 4, 3, 1],
... [1, 0, 4, 5],
... ]
The matrix
variable holds a Python list that contains four nested lists. Each nested list represents a row in the matrix. The rows store four items or numbers each. Now say that you want to turn this matrix into the following list:
[9, 3, 8, 3, 4, 5, 2, 8, 6, 4, 3, 1, 1, 0, 4, 5]
How do you manage to flatten your matrix and get a one-dimensional list like the one above? In this tutorial, you’ll learn how to do that in Python.
Free Bonus: Click here to download the free sample code that showcases and compares several ways to flatten a list of lists in Python.
Take the Quiz: Test your knowledge with our interactive “How to Flatten a List of Lists in Python” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
How to Flatten a List of Lists in PythonIn this quiz, you'll test your understanding of how to flatten a list in Python. Flattening a list involves converting a multidimensional list, such as a matrix, into a one-dimensional list. This is a common operation when working with data stored as nested lists.
How to Flatten a List of Lists With a for
Loop
How can you flatten a list of lists in Python? In general, to flatten a list of lists, you can run the following steps either explicitly or implicitly:
- Create a new empty list to store the flattened data.
- Iterate over each nested list or sublist in the original list.
- Add every item from the current sublist to the list of flattened data.
- Return the resulting list with the flattened data.
You can follow several paths and use multiple tools to run these steps in Python. Arguably, the most natural and readable way to do this is to use a for
loop, which allows you to explicitly iterate over the sublists.
Then you need a way to add items to the new flattened list. For that, you have a couple of valid options. First, you’ll turn to the .extend()
method from the list
class itself, and then you’ll give the augmented concatenation operator (+=
) a go.
To continue with the matrix
example, here’s how you would translate these steps into Python code using a for
loop and the .extend()
method:
>>> def flatten_extend(matrix):
... flat_list = []
... for row in matrix:
... flat_list.extend(row)
... return flat_list
...
Inside flatten_extend()
, you first create a new empty list called flat_list
. You’ll use this list to store the flattened data when you extract it from matrix
. Then you start a loop to iterate over the inner, or nested, lists from matrix
. In this example, you use the name row
to represent the current nested list.
In every iteration, you use .extend()
to add the content of the current sublist to flat_list
. This method takes an iterable as an argument and appends its items to the end of the target list.
Now go ahead and run the following code to check that your function does the job:
>>> flatten_extend(matrix)
[9, 3, 8, 3, 4, 5, 2, 8, 6, 4, 3, 1, 1, 0, 4, 5]
That’s neat! You’ve flattened your first list of lists. As a result, you have a one-dimensional list containing all the numeric values from matrix
.
With .extend()
, you’ve come up with a Pythonic and readable way to flatten your lists. You can get the same result using the augmented concatenation operator (+=
) on your flat_list
object. However, this alternative approach may not be as readable:
>>> def flatten_concatenation(matrix):
... flat_list = []
... for row in matrix:
... flat_list += row
... return flat_list
...
Read the full article at https://realpython.com/python-flatten-list/ »
[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]
December 22, 2024 at 07:30PM
Click here for more details...
=============================
The original post is available in Real Python by
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================
Post a Comment