Python: Flatten Lists of Lists (4 Ways) • datagy (2023)

In this tutorial, you’ll learn how to use Python to flatten lists of lists! You’ll learn how to do this in a number of different ways, including with for-loops, list comprehensions, the itertools library, and how to flatten multi-level lists of lists using, wait for it, recursion! Let’s take a look at what you’ll learn in this tutorial!

The Quick Answer: Use a Python List Comprehension to Flatten Lists of Lists

Python: Flatten Lists of Lists (4 Ways) • datagy (1)

Table of Contents

What is a Python List of Lists?

In Python, a list of a lists is simply a list that contains other lists. In fact, lists of lists in Python can even contain other lists of lists! We can say that a list that contains only one other layer of lists is called a 2-dimensional list of lists. When one or more of these lists contain another list, we say they’re called 3-dimensional. This continues onwards, as we add more and more layers.

When you convert a list of lists, or a 2-dimensional array, into a one-dimensional array, you are flattening a list of lists. Learn four different ways to do this in this tutorial!

(Video) Python List Comprehensions | Python Tutorial | Why and How to Use Them | Learn Python Programming

Let’s take a look at a simple list of lists in Python, so that you can have a visual depiction of what they actually look like:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

When we try to access the third item, index position 2, we can print out what it contains:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print(list_of_lists[2])# Returns: [4, 5, 6]

We can see here that the third item of our list list_of_lists is actually another list. This is what we mean by lists of lists – they are lists that contain other lists.

In the next section, you’ll learn how to use a naive method, a for-loop, to flatten a list of lists.

How to Use a Python For Loop to Flatten Lists of Lists?

Now that you know what a Python list of lists is, let’s see how we can use a Python for-loop to flatten them!

In our for-loop, we’ll loop over each item in the list and add each item to a new list.

Let’s see how we can accomplish this with Python:

(Video) Python For Loops | Python Tutorial | Use For Loops | Learn Python Programming | If, Else, Break

# Use a for-loop to flatten a list of listslist_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]flat_list = list()for sub_list in list_of_lists: flat_list += sub_listprint(flat_list)# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Let’s break down what we’ve done here step-by-step:

  1. We loaded our list_of_lists
  2. We generated a new list, called flat_list
  3. We looped over each item, or list, in the list of lists and added each item’s values to our flat_list

Now that you’ve used a for-loop to flatten a list of lists, let’s learn how you can use list comprehensions to flatten them!

Want to learn more? Check out my in-depth tutorial on Python for-loops here!

How to Use a List Comprehension in Python to Flatten Lists of Lists?

Python list comprehensions are elegant, Pythonic replacements for Python for-loops. In fact, any list comprehension can actually be expressed as a for-loop (though the reverse isn’t necessarily true).

So why write a list comprehension when a for-loop might do? There are a number of benefits to using list comprehensions – let’s take a quick look at them here:

  1. You don’t need to instantiate a new empty list
  2. You can write it over one line, rather than needing to split it out over multiple lines
  3. They’re more Pythonic than for-loops

Want to learn more? Check out my in-depth tutorial on Python list comprehensions here!

Let’s take a look at how Python list comprehension look:

(Video) Python Filter Function - Intermediate Python Tutorial

Python: Flatten Lists of Lists (4 Ways) • datagy (2)

Now, let’s see how we can use list comprehensions to flatten Python lists of lists:

 # Use a List Comprehension to Flatten a List of Listslist_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]flat_list = [item for sublist in list_of_lists for item in sublist]print(flat_list)# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Keep in mind that this does exactly what the for-loop is doing. The syntax can take a bit of getting used to, but once you master it, it becomes second nature and saves you a good amount of time!

Both of the methods we’ve covered off so far don’t require you to import a different library. Now, let’s take a look at how we can use the itertools library to flatten Python lists of lists.

In particular, we’ll use the chain function to to loop over each individual item in the larger list and add it to the larger list. Finally, since the chain function would return an itertools.chain object, we need to convert it back to a list.

Let’ see how we can do this here:

from itertools import chainlist_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]flat_list = list(chain(*list_of_lists))print(flat_list)# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Since we rely on variable unpacking, it’s not immediately clear what’s happening in the code (as some other custom functions might). Because of this, make sure you document your code well!

Check out some other Python tutorials on, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

(Video) Python Collections Library deque - Intermediate Python Tutorial

How to Flatten Multi-level Lists of Lists in Python?

Now, there may be times that you encounter more complex lists, such as the one shown below. Using one of these methods shown above won’t work, as they require you to have similar levels within their lists.

list_of_lists = [1, [2, 3], [4, [5, 6]], [7, 8], 9]

We can see that in our lists, we have some items at the root level, and some lists embedded in other lists.

In order to flatten this list of lists, we will need to think a bit more creatively. In particular, we can develop a function that calls itself recursively to unpack lists of lists.

Let’s see how we can do this in Python (thanks for the fix, Chengju!):

# Flatten a multi-level list of lists with recursionlist_of_lists = [1, [2, 3], [4, [5, 6]], [7, 8], 9]def flatten_list(list_of_lists, flat_list=[]): if not list_of_lists: return flat_list else: for item in list_of_lists: if type(item) == list: flatten_list(item, flat_list) else: flat_list.append(item) return flat_listflat_list = flatten_list(list_of_lists)print(flat_list)# Returns: [1, 2, 3, 4, 5, 6, 7, 8, 9]

This example is a bit more complex, so let’s see what we’ve done here:

  1. We generate a new function flatten_list that takes a list of lists as an input as well as an empty list by default
  2. We evaluate is our flat_list is still an empty list. If it is, we return itself. Otherwise, we loop over each item and process the steps below.
  3. We then loop over each item in the list
  4. We check if the type of the item is a list:
    1. If it is a list, then we call the function again
    2. If it isn’t, we append the item to our flat_list

We can see here that this works quite simply and is actually adaptable to any number of nesting!


In this post, you learned how to use Python to flatten lists of lists. You also learned what lists of lists in Python actually are. In addition to this, you learned how to use for-loops and list comprehensions to flatten lists of lists in Python. You also learned how to use the itertools library to flatten lists of lists. Finally, you learned how to use recursion to multi-level lists of lists.

(Video) Python Map Function

To learn more about the itertools library, check out the official documentation here.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • How to Check if a Python List is Empty
  • How to Iterate (Loop) Over a List in Python
  • Python List Extend: Add Elements to a List
  • Python: Find List Index of All Occurences of an Element


What is the most efficient way to flatten a list of lists in Python? ›

You can flatten a Python list using a list comprehension, a nested for loop, and the itertools. chain() method. The list comprehension is the most “Pythonic” method and is therefore favoured in most cases. While nested for loops are effective, they consume more lines of code than a list comprehension.

How do you flatten a multi list in Python? ›

In Python, you can flatten a list of lists (nested list, 2D list) using itertools. chain. from_iterable() , sum() , and list comprehensions. Use ravel() or flatten() to flatten a NumPy array ndarray .

How do you flatten a list of lists with a list comprehension? ›

To flatten a list of lists, use the list comprehension statement [x for l in lst for x in l] . To modify all elements in a list of lists (e.g., increment them by one), use a list comprehension of list comprehensions [[x+1 for x in l] for l in lst] .

How do you flatten multiple nested lists in Python? ›

Python Program to Flatten a Nested List
  1. Using list comprehension access the sublist from my_list , then access each element of the sublist.
  2. Each element num is stored in flat_list .

Is there a flatten function in Python? ›

flatten() method in Python is used to return a copy of a given array in such a way that it is collapsed into one dimension.

How do you reduce time complexity in a list in Python? ›

The easiest way to reduce the time complexity is to avoid a for loop whenever possible. Ideally, you may want to check the time complexity of time Python functions you use, and refactor your code by selecting the less complex functions.

How do you flatten a list of iterables? ›

One way to flatten an iterable-of-iterables is with a for loop. We can loop one level deep to get each of the inner iterables. And then we loop a second level deep to get each item from each inner iterable.

How do I flatten a list in Python using NumPy? ›

To flatten a NumPy array of arrays, say arr , use the np. concatenate(arr). ravel() function call. The result will be a one-dimensional (1D) flattened NumPy array of values.

How do you flatten an array of arrays in Python? ›

Flatten a NumPy array with reshape(-1)

You can also use reshape() to convert the shape of a NumPy array to one dimension. If you use -1 , the size is calculated automatically, so you can flatten a NumPy array with reshape(-1) . reshape() is provided as a method of numpy.

How do you flatten a list of lists using recursion in Python? ›

Python Program to Flatten a Nested List using Recursion
  1. Initialize a variable to a nested list.
  2. Pass the list as an argument to a recursive function to flatten the list.
  3. In the function, if the list is empty, return the list.

How list comprehension is faster? ›

List Comprehensions. This code will create a new list called squares that contains the square of each number in the original list. List comprehensions are often faster than loops because they use a more optimized internal mechanism for iterating over the collection.

What is the difference between list generator and list comprehension? ›

List comprehensions return the entire list, and the generator expression returns only the generator object. The values will be the same as those in the list, but they will be accessed one at a time by using the next() function. This is what makes list comprehensions faster than generator expressions.

How do you flatten a dataset in Python? ›

  1. Step 1 - Import the library. import numpy as np. We have only imported numpy which is needed.
  2. Step 2 - Setting up the Data. We have created a matrix using array and we will flatten this. ...
  3. Step 3 - Calculating inverse of matrix. We can flatten the matrix by using flatten function with no parameters.
May 20, 2022

How do you flatten an array? ›

You use the flat() method for concatenating sub-arrays recursively into a single array. The flat() method takes a depth value as its parameter which is optional depending on the depth of the array you wish to flatten (concatenate). The flat() method takes in 1 as a depth by default.

How do you flatten a shallow list in Python? ›

A simple and straightforward solution is to append items from sublists in a flat list using two nested for loops. A more compact and Pythonic solution is to use chain() function from itertools module.

How do you flatten a list in a list Python? ›

How to flatten a list of lists in Python
  1. Looping and List comprehension. This is the easiest way to flatten a list. ...
  2. itertools. chain(*nested_list) ...
  3. itertools. chain. ...
  4. functools. reduce(function, nested_list) ...
  5. numpy.concatenate(nested_list) Returns merged list instead of an iterator. ...
  6. numpy. array(nested_list).

What is the difference between NumPy Ravel and flatten? ›

What is the difference between the Numpy flatten and ravel functions? The main functional distinction is that flatten is a function of an ndarray object and hence only works with genuine numpy arrays. ravel(), on the other hand, is a library-level function that may be invoked on any object that can be correctly parsed.

What is the difference between flatten and Ravel? ›

flatten always returns a copy. ravel returns a view of the original array whenever possible. This isn't visible in the printed output, but if you modify the array returned by ravel, it may modify the entries in the original array. If you modify the entries in an array returned from flatten this will never happen.

What is the fastest data structure in Python? ›

Space-time tradeoff. The fastest way to repeatedly lookup data with millions of entries in Python is using dictionaries. Because dictionaries are the built-in mapping type in Python thereby they are highly optimized.

Is Python list faster than dictionary? ›

The list is an ordered collection of data, whereas the dictionaries store the data in the form of key-value pairs using the hashtable structure. Due to this, fetching the elements from the list data structure is quite complex compared to dictionaries in Python. Therefore, the dictionary is faster than a list in Python.

How do I reduce the size of a list in Python? ›

Python offers a function called reduce() that allows you to reduce a list in a more concise way. The reduce() function applies the fn function of two arguments cumulatively to the items of the list, from left to right, to reduce the list into a single value.

How do you flatten a nested array? ›

Different methods to flatten an array
  1. a. Using concat() and apply() ...
  2. b. Using the spread operator. ...
  3. c. Using the reduce method. ...
  4. Obtaining a flattened array by specifying the depth. The depth of an array is the number of levels of bracket pairs in the array. ...
  5. a. Using the flat() method.

How do you flatten a nested array of objects? ›

JavaScript Flatten Deeply Nested Array of Objects Into Single Level Array
  1. Using Plain JavaScript (es6) const familyTree = [ // as above ]; const getMembers = (members) => { let children = []; const flattenMembers = members. ...
  2. Using Lodash flatMapDeep Method.
Dec 26, 2022

How do you flatten an iterator in Python? ›

Flatten Nested List Iterator in Python
  1. In the initializing section, it will take the nested list, this will work as follows −
  2. set res as empty list, index := 0, call getVal(nestedList)
  3. The getVal() will take nestedIntegers, this will work as −
  4. for i in nestedIntegers.
Apr 29, 2020

What is the flatter method? ›

Prototype - flatten() Method

This method returns a flat (one-dimensional) version of the array. Nested arrays are recursively injected inline. This can prove very useful when handling the results of a recursive collection algorithm.

What is the function to flatten an array in Python? ›

The numpy. ndarray. flatten() function is used to get a copy of an given array collapsed into one dimension. This function is useful when we want to convert a multi-dimensional array into a one-dimensional array.

What is the flatten method in pandas? ›

Flattening pandas dataframe means changing the shape of the dataframe to one dimension. You can say changing the values of the datasets to the list. Suppose you have to pandas dataframe with two-column and its four corresponding rows or records. Then all the columns and rows will flatten to a single list.

How do you flatten a 3d array to 1d in Python? ›

You can use the ndarray. flatten, in your example it would be matrix. flatten() . This returns the flattened version of your matrix.

How to convert list to array in Python? ›

There are three methods to convert list to array in python and these are, by using the array(), by using the numpy. array(), or by using the numpy. asarray().

How do you convert a list to a 2d array in Python? ›

Use the reshape() method to transform the shape of a NumPy array ndarray . Any shape transformation is possible. This includes but is not limited to transforming from a one-dimensional array to a two-dimensional array. By using -1 , the size of the dimension is automatically calculated.

How do you break a list in a list Python? ›

How to Split a Python List or Iterable Into Chunks
  1. Store the Matrix in a Row-Major or Column-Major Order.
  2. Flatten, Split, and Reshape a NumPy Array.
  3. Find the Splitting Points in Space.
  4. Retain Spatial Information in a Bounds Object.
Feb 8, 2023

How to flatten a dictionary with nested lists and dictionaries in Python? ›

The function allows for a custom separator and will preserve the order of the terms.
  1. Starting Structure. Our function will require recursion to properly function. ...
  2. Outlining the recurse() Function. ...
  3. Completing the flatten() Function. ...
  4. Testing Out the Function.
Sep 26, 2019

How to convert list string to list float in Python? ›

Using float() Function

float() function is the most common way to convert the string to the float value. The float function takes the parameter y, which is a string, and would then convert the string to a float value and return its float value.

What is the faster alternative to list in Python? ›

In conclusion, we have seen that there are two ways to represent a list in Python: using square brackets [] and using the list() function. While both methods create a list, the square bracket method is faster and more efficient than using the list() function.

Which is faster filter () or list comprehension? ›

Regarding performance, we're also seeing similar results to the ones obtained for map() . List comprehensions are fastest, followed by filter() with a predefined filter function, and filter() with an ad-hoc lambda function comes in last.

Is map faster than list comprehension in Python? ›

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.

Are generators more efficient than lists Python? ›

The generator yields one item at a time — thus it is more memory efficient than a list. For example, when you want to iterate over a list, Python reserves memory for the whole list. A generator won't keep the whole sequence in memory, and will only “generate” the next element of the sequence on demand.

Is list comprehension faster than iteration? ›

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration. This is slow.

Is list comprehension faster than Lambda? ›

Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.

What is data flattening? ›

Data flattening is associated with transforming data into plain text files stored in file systems rather than in databases or data warehouses. Flat files are records that generally consist of single portions of data, which can be, for example, tabular spreadsheet files.

How to do data scaling in Python? ›

There are different methods for scaling data, in this tutorial we will use a method called standardization. Where z is the new value, x is the original value, u is the mean and s is the standard deviation. Now you can compare -2.1 with -1.59 instead of comparing 790 with 1.0.

What is data reshaping in Python? ›

Python has operations for rearranging tabular data, known as reshaping or pivoting operations. For example, hierarchical indexing provides a consistent way to rearrange data in a DataFrame. There are two primary functions in hierarchical indexing: stack(): rotates or pivots data from columns to rows.

How do you flat an array without a flat method? ›

Using .apply(_) and .concat(_) method

one can use these two methods for flattening an array. We pass two arguments to the apply(_) method - an empty array and the array we want to flatten(arr), then concatenate all the elements(sub-arrays) passed into an empty array. Thus obtaining a 1-dimensional array.

Does flatten modify the original array? ›

Flattening a Multi-dimensional array means transforming it into a one-dimensional array. The method used to arrive at this is the flatten! method. However, flatten! will not modify the original array or the array that calls the function.

What is the difference between flatten and flatMap? ›

flatMap is similar to flatten , but flatten only acts on the values of the arrays, while flatMap can act on values and indices of items in the array.

How do you flatten an array of tuples in Python? ›

One method to flatten tuples of a list is by using the sum() method with empty lust which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple. Method 2: Another method is using a method from Python's itertools library.

What is the most efficient way to loop through a list in Python? ›

Using a 'for' loop, we can make Python loop through the list and perform the task. This is the most efficient way to loop through a list with ease irrespective of whether the list contains 10 or 1000 items.

What is the most efficient way to check if a list is empty Python? ›

Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.

What is the fastest way to empty a list Python? ›

The clear() method removes all the elements from a list.

How do you flatten a list in NumPy Python? ›

Algorithm (Steps)
  1. Use the import keyword, to import the numpy module with an alias name(np).
  2. Use the numpy. ...
  3. Print the given input 2-Dimensional matrix.
  4. Apply flatten() function (flattens a matrix to 1-Dimension) of the numpy module on the input matrix to flatten the input 2D matrix to a one-dimensional matrix.
Oct 31, 2022

What are the looping techniques on list in Python? ›

Example 1:
  1. # first, initialize the list.
  2. list = [ 1 , 4, 6, 7, 1, 2, 4 ]
  3. # using sorted() to print the list in sorted order.
  4. print ("The list in sorted order is : ")
  5. for a in sorted(list) :
  6. print (a, end = " ")
  7. print ("\r")
  8. # now use the sorted() function and set() function for printing the list in sorted order.

Are loops or recursion more efficient? ›

Speed. We can say that if we keep all other factors the same, recursion is slower than looping. This is so because recursion adds function calling overhead to its execution. And that makes it slower than iteration.

Which kind of loop is most ideal for iterating over a list? ›

The for loop is probably the most common and well known type of loop in any programming language. For can be used to iterate through the elements of an array: For can also be used to perform a fixed number of iterations: By default the increment is one.

How do you check if a list exists and not empty in Python? ›

Use the if conditional statement to check whether the list object is pointing to the literal [] i.e checking whether the list is equal to [] or not. Print “Empty list”, if the condition is true. Else print “List is not empty”, if the condition is false.

What method checks if a list is empty Python? ›

How To Check if a List Is Empty in Python Using the len() Function. You can use the len() function in Python to return the number of elements in a data structure. Using the len() function, we printed the length of the people_list list which had four elements.

How do you clean up a list in Python? ›

Python List clear()
  1. Syntax of List clear() The syntax of clear() method is: list.clear()
  2. clear() Parameters. The clear() method doesn't take any parameters.
  3. Return Value from clear() The clear() method only empties the given list. ...
  4. Example 1: Working of clear() method.

What is the fastest way to remove duplicates from a list in Python? ›

fromkeys() This is the quickest way to accomplish the goal of removing duplicates from the Python list. This method first removes duplicates before returning a dictionary that has been converted to a list. In addition, this method works well with strings.

How do you clean data from a list in Python? ›

Remove an item from a list in Python (clear, pop, remove, del)
  1. Remove all items: clear()
  2. Remove an item by index and get its value: pop()
  3. Remove an item by value: remove()
  4. Remove items by index or slice: del.
  5. Remove items that meet the condition: List comprehensions.
May 6, 2023


1. Python Collections Library Counter Counting Objects with Python
2. Python Excel Automation #1 - Consolidate Excel Workbooks, Python Pivot Tables, and Excel Charts
3. Python Pivot Tables Tutorial | Create Pandas Pivot Tables | Python Tutorial | Examples, Subtotals
4. Style Python Pandas DataFrames! (Conditional Formatting, Color Bars and more!)
5. Histogram in Python - Matplotlib Tutorial - Pandas Tutorial - Define bins, add style, log scale
6. Moving Average (Rolling Average) in Pandas and Python - Set Window Size, Change Center of Data


Top Articles
Latest Posts
Article information

Author: Laurine Ryan

Last Updated: 10/04/2023

Views: 5397

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.