• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Using Python to Flatten Array of Arrays

Using Python to Flatten Array of Arrays

August 26, 2022 Leave a Comment

To flatten a list of lists in Python, the easiest way is to use list comprehension.

list_of_lists = [[1], [2, 3], [4, 5, 6]]

flattened_list = [value for sub_list in list_of_lists for value in sub_list]

print(flattened_list)

#Output:
[1, 2, 3, 4, 5, 6]

If you have a list of lists which also contain lists of lists, you can use a recursive function to flatten all levels of the list of lists.

list_of_lists = ["a", ["b", "c"], [1, [2, 3]], [4, 5], 6]

def flatten_list(lst): 
    flat_list = []
    for item in lst:
        if type(item) == list:
            flat_list = flat_list + flatten_list(item)
        else:
            flat_list.append(item)
    return flat_list

print(flatten_list(list_of_lists))

#Output:
['a', 'b', 'c', 1, 2, 3, 4, 5, 6]

When working with collections of data, the ability to easily be able to manipulate them and change the structure is valuable.

One such case is if you have an array of arrays and want to flatten them into one array.

Arrays in Python are called lists, and we can easily flatten a list in Python.

To flatten a list of lists in Python, the easiest way is to use list comprehension. This method works if you have a list of lists and each of those sub-lists do not contain lists.

The idea here is that for each list, we want to get all of the values and then store them in a new list.

Below shows you how to use list comprehension to flatten a list of lists in Python.

list_of_lists = [[1], [2, 3], [4, 5, 6]]

flattened_list = [value for sub_list in list_of_lists for value in sub_list]

print(flattened_list)

#Output:
[1, 2, 3, 4, 5, 6]

Using Recursion to Flatten List of Multi-dimensional Lists in Python

If you have a list of objects where some are not lists and others are lists or lists of lists, we need to do some more work to flatten a list like this.

You can use recursion to flatten a list of multi-dimensional lists in Python.

The idea here is that you have to loop over each item of the list and then if that item is of type list, we need to get the values of that list as well.

Then, you can use the concatenation operator + to add the list items together.

Below is a function which will flatten a list of lists with multiple dimensions in Python.

list_of_lists = ["a", ["b", "c"], [1, [2, 3]], [4, 5], 6]

def flatten_list(lst): 
    flat_list = []
    for item in lst:
        if type(item) == list:
            flat_list = flat_list + flatten_list(item)
        else:
            flat_list.append(item)
    return flat_list

print(flatten_list(list_of_lists))

#Output:
['a', 'b', 'c', 1, 2, 3, 4, 5, 6]

Hopefully this article has been useful for you to learn how to flatten lists in Python.

Other Articles You'll Also Like:

  • 1.  Drop Duplicates pandas – Remove Duplicate Rows in DataFrame
  • 2.  How to Group and Aggregate By Multiple Columns in Pandas
  • 3.  Remove Decimal from Float in Python
  • 4.  Append Multiple Elements to List Using Python
  • 5.  How to Multiply All Elements in List Using Python
  • 6.  Remove Duplicates from Sorted Array in Python
  • 7.  Using Lambda Expression with max() in Python
  • 8.  Get Random Value from Dictionary in Python
  • 9.  pandas unique – Get Unique Values in Column of DataFrame
  • 10.  Python rjust Function – Right Justify String Variable

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy