Flattening a List of Lists
00:00 Flattening a List of Lists. Flattening a list of lists is a common task in Python. Let’s say you have a list of lists and need to flatten it into a single list containing all the items from these original nested lists.
00:15
You can use any of several approaches to flattening lists in Python. For example, you can use a for
loop, as in the code seen on- screen. Inside flatten_list()
, the loop iterates over all the nested lists contained in a_list
.
00:33
Then it concatenates them in flat
using an augmented assignment operation (+=
).
00:41
As the result, you get a flat list with all the items from the original nested lists. But hang on! You’ve already learned how to use sum()
to concatenate sequences in this course.
00:55 Can you use this feature to flatten a list of lists just like you did in the example scene? Yes. That was quick. A single line of code and a matrix is now a flat list.
01:09
However, using sum()
doesn’t seem to be the fastest solution. An important drawback of any solution that implies concatenation is that behind the scenes, every intermediate step creates a new list.
01:23 This can be pretty wasteful in terms of memory usage. The list that is eventually returned is just the most recently created list out of all the lists that were created at each round of concatenation.
01:35 Using a list comprehension instead ensures that you create and return only one list.
02:04
This new version of flatten_list()
is more efficient and less wasteful in terms of memory usage. However, nested comprehensions can be challenging to read and understand.
02:15
Using .append()
is probably the most readable and Pythonic way to flatten a list of lists.
02:33
In this version of flatten_list()
, someone reading your code can see that the function iterates over every sublist
in a_list
. Inside this first for
loop, it iterates over each item
in sublist
to finally populate the new flat
list with .append()
. Just like the comprehension from earlier, this solution creates only one list in the process.
02:54 Another advantage of this solution is that it’s very readable.
03:01
In the next section of the course, you’ll take a look at some alternatives to using sum()
.
Become a Member to join the conversation.