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

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 - 6 Ways to Flatten a List of Lists (Nested Lists) TUTORIAL

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) Flatten A List Of Lists In Python

# 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 : How to make a flat list out of a list of lists

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 datagy.io, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

(Video) How To Flatten Nested Lists in Python

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:

# 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 flat_list == []: return flat_list else: for item in list_of_lists: if type(item) == list: flatten_list(item) 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!

Conclusion

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) How to Flatten a List of Lists in Python | Code Leaks

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

FAQs

How do you flatten a multi list in Python? ›

#3. Flatten Multi-Level Lists
  1. Initialize the data as shown in the example and name it as data.
  2. Initialize an empty list called flat_list.
  3. Write a function called flatten_list. ...
  4. Invoke the function with data.
  5. The function will fill all the elements in the flat_list list.
  6. Print the flat_list to check the output.
1 Nov 2020

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

There are three ways to flatten a Python list:
  1. Using a list comprehension.
  2. Using a nested for loop.
  3. Using the itertools. chain() method.
4 Jan 2021

How much faster are list comprehensions? ›

The list comprehension is 50% faster.

How do I flatten a multiple nested list? ›

To flatten a nested list we can use the for loop or the While loop or recursion or the deepflatten() Method. Other techniques include importing numerous external Python libraries and using their built-in functions.

How do you flatten data in Python? ›

The flatten() function is used to get a copy of an given array collapsed into one dimension. 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise.

What is the flatten method in pandas? ›

Return a copy of the array collapsed into one dimension. Whether to flatten in C (row-major), Fortran (column-major) order, or preserve the C/Fortran ordering from a . The default is 'C'.

How do I flatten a list in NumPy? ›

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 tuples in Python? ›

How to Flatten List of Tuples in Python
  1. Using sum. This is the easiest and fastest method to convert a list of tuples. ...
  2. Using itertools. itertools is a useful library that allows you to easily work with iterable data structure like lists. ...
  3. Using List Comprehension. ...
  4. Using extend.
25 Jun 2021

Are list comprehensions more efficient? ›

Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.

Are Python list comprehensions faster than for loops? ›

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.

Is list comprehension faster than Numpy? ›

Numpy is more the 61 times faster than list comprehension, but sometimes we need to use this value as a list. Even as a list, the method Numpy is at least 2,34 faster than other methods.

How do I merge two nested lists in Python? ›

First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.

How do you reduce the size of a list? ›

Flattening Regular Lists
  1. Method 1: Looping Over Elements. In this approach, we will create a new list to hold each element as we discover them. ...
  2. Method 2: List Comprehension. ...
  3. Method 3: The sum Function. ...
  4. Edge Case 1: 2-Dimensional Data. ...
  5. Edge Case 2: Multi-Dimensional Data. ...
  6. Edge Case 1: Strings & Bytes.
28 Nov 2021

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

Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. For Python >= 3.3, change the import to from collections.

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

Step-by-step Approach:

Firstly, we try to initialize a variable into the linked list. Then, our next task is to pass our list as an argument to a recursive function for flattening the list. In that recursive function, if we find the list as empty then we return the list.

How do you combine lists in Python? ›

In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.

How do you make a list of lists in one list Python? ›

Using append() function to create a list of lists in Python. What append() function does is that it combines all the lists as elements into one list.

What is the flatter 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.

How do you flatten an array? ›

Different methods to flatten an array
  1. a. Using concat() and apply() let flatArray = []. concat. ...
  2. b. Using the spread operator. let flatArray = []. concat(...arr); //Output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] ...
  3. c. Using the reduce method. let flatArray = arr. reduce((acc, curVal) => { return acc.
5 Aug 2022

What is a Flatten function? ›

FLATTEN is a table function that takes a VARIANT, OBJECT, or ARRAY column and produces a lateral view (i.e. an inline view that contains correlation referring to other tables that precede it in the FROM clause). FLATTEN can be used to convert semi-structured data to a relational representation.

How do you flatten a list in a DataFrame? ›

Solution 1: Flatten pandas dataframe using Numpy

The first method to flatten the pandas dataframe is through NumPy python package. There is a function in NumPy that is numpy. flatten() that perform this task.

How do you make an array flat in Python? ›

By using ndarray. flatten() function we can flatten a matrix to one dimension in python. order:'C' means to flatten in row-major. 'F' means to flatten in column-major.

How do I flatten a DataFrame in PySpark? ›

How to Flatten Json Files Dynamically Using Apache PySpark(Python...
  1. Step1:Download a Sample nested Json file for flattening logic.
  2. Step2: Create a new python file flatjson.py and write Python functions for flattening Json.
  3. Step3: Initiate Spark Session.
  4. Step4:Create a new Spark DataFrame using the sample Json.

What is flatten function in Python? ›

flatten() function return a copy of the array collapsed into one dimension. Syntax : numpy.ndarray.flatten(order='C') Parameters : order : [{'C', 'F', 'A', 'K'}, optional] 'C' means to flatten in row-major (C-style) order.

What is the difference between Ravel and flatten? ›

Ravel is faster than flatten() as it does not occupy any memory. Flatten() is comparatively slower than ravel() as it occupies memory. Ravel is a library-level function. Flatten is a method of an ndarray object.

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

You can use itertools. chain. from_iterable() , sum() , and list comprehensions. Use ravel() or flatten() to flatten a NumPy array ndarray .

How do you flatten an array of tuples? ›

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.

How do I make a list out of a list of tuples? ›

If you're in a hurry, here's the short answer:

Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.

How do you flatten a nested tuple? ›

Flattening Nested Tuples

To solve the problem is by finding all the nested tuples in each tuple element of the container. And then flatten it to a normal tuple with all elements of the nested as individual elements.

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

How to Flatten List of Tuples in Python
  1. Using sum. This is the easiest and fastest method to convert a list of tuples. ...
  2. Using itertools. itertools is a useful library that allows you to easily work with iterable data structure like lists. ...
  3. Using List Comprehension. ...
  4. Using extend.
25 Jun 2021

How do I flatten a list in NumPy? ›

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 3d list in Python? ›

You can use itertools. chain. from_iterable() , sum() , and list comprehensions. Use ravel() or flatten() to flatten a NumPy array ndarray .

What is the flatten method in pandas? ›

Return a copy of the array collapsed into one dimension. Whether to flatten in C (row-major), Fortran (column-major) order, or preserve the C/Fortran ordering from a . The default is 'C'.

How do you flatten an array of tuples? ›

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.

How do you flatten an array in Python? ›

By using ndarray. flatten() function we can flatten a matrix to one dimension in python. order:'C' means to flatten in row-major. 'F' means to flatten in column-major.

How do I make a list out of a list of tuples? ›

If you're in a hurry, here's the short answer:

Use the list comprehension statement [list(x) for x in tuples] to convert each tuple in tuples to a list. This also works for a list of tuples with a varying number of elements.

What is the flatter 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 flatten function in Python? ›

flatten() function return a copy of the array collapsed into one dimension. Syntax : numpy.ndarray.flatten(order='C') Parameters : order : [{'C', 'F', 'A', 'K'}, optional] 'C' means to flatten in row-major (C-style) order.

How do you flatten an array? ›

Different methods to flatten an array
  1. a. Using concat() and apply() let flatArray = []. concat. ...
  2. b. Using the spread operator. let flatArray = []. concat(...arr); //Output: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ] ...
  3. c. Using the reduce method. let flatArray = arr. reduce((acc, curVal) => { return acc.
5 Aug 2022

How do I merge two nested lists in Python? ›

First, flatten the nested lists. Take Intersection using filter() and save it to 'lst3'. Now find elements either not in lst1 or in lst2, and save them to 'temp'. Finally, append 'temp' to 'lst3'.

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

To convert a list to array in Python, use the np. array() method. The np. array() is a numpy library function that takes a list as an argument and returns an array containing all the list elements.

How do you split a 2D list in Python? ›

  1. Given a nested 2D list, the task is to split the nested list into two lists such that first list contains first elements of each sublists and second list contains second element of each sublists. ...
  2. Method #2: Using list comprehension.
  3. Method #3: Using operator.itemgetter()
  4. Method #4 : Using extend() method.
29 Jul 2022

Videos

1. How to flatten a nested list in Python
(Jie Jenn)
2. How to flatten a list in Python? What is a flattened list? List Operations
(AI Cluster)
3. Python Programming 42 - Working with List of Lists (2D Lists)
(Caleb Curry)
4. PARSE LIST OF LISTS OF DICTIONARIES USING PYTHON | JSON | NESTED LISTS
(Mr Fugu Data Science)
5. Python Code Challenge - Flatten Nested List
(Very Academy)
6. (Easy) Python | Unpacking and flattening lists containing lists (with Code)
(PythonBobby)

Top Articles

Latest Posts

Article information

Author: Kieth Sipes

Last Updated: 09/05/2022

Views: 6410

Rating: 4.7 / 5 (47 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Kieth Sipes

Birthday: 2001-04-14

Address: Suite 492 62479 Champlin Loop, South Catrice, MS 57271

Phone: +9663362133320

Job: District Sales Analyst

Hobby: Digital arts, Dance, Ghost hunting, Worldbuilding, Kayaking, Table tennis, 3D printing

Introduction: My name is Kieth Sipes, I am a zany, rich, courageous, powerful, faithful, jolly, excited person who loves writing and wants to share my knowledge and understanding with you.