Flattening a List of Lists in Python (Overview)
Sometimes, when you’re working with data, you may have the data as a list of nested lists. A common operation is to flatten this data into a one-dimensional list in Python. Flattening a list involves converting a multidimensional list, such as a matrix, into a one-dimensional list.
In this video course, you’ll learn how to do that in Python.
00:00
Welcome to Flattening a List of Lists in Python My name is Christopher and I will be your guide. In this course, you’ll learn about flattening nested lists, how to use iterators, the chain()
, and reduce()
functions, and how to time your code in order to determine its performance.
00:18 The code in this course was tested using Python 3.12. All the code should work with any Python 3. There are a few small references to functions available in specific Python versions, but I’ll point them out as I go along.
00:35 A list of lists is a common data structure, but doing data analysis on a list of lists can be expensive. Many tools expect a stream of values, and the additional structure of a nested list means you can’t use these tools directly.
00:50 The answer is to flatten your list of lists, creating a single list comprised of the values found inside the nested inner lists, essentially removing the inner structure of the original.
01:01 There are many different ways to flatten a list of lists, and I’ll be covering several approaches and why you might choose one over the other.
Become a Member to join the conversation.