Home Python How to flatten a list in Python

How to flatten a list in Python

The method of eliminating a dimension from a list is known as flattening a list. A dimension is a coordinate that is needed to locate an object in a list. Multiple dimensions can be present in a Python list. This means you’ve got a list inside a list. These lists, also known as “nested lists,” can be transformed back to standard lists.

This means you can combine all of the values from several lists into a single one. The process of converting a list of lists into a single list is known as “flattening a list.”

Flatten List in Python

It is possible to flatten list in Python in various ways:

  • Using a comprehension strategy based on a list.
  • Using a nested for loop
  • The itertools.chain() method
  • Functools – reduce
  • NumPy – concatenate
  • NumPy – flat
  • Summing inner lists

We’ll go over these methods in this tutorial. We’ll also illustrate using various examples so you can get started flattening lists in your code.

Python: Using a List Comprehension to Flatten a List

A Python list comprehension creates a new list from the contents of another one. By defining requirements or adjustments within the comprehension, you can customize each feature into your new list.

Comprehensions are syntactic sugar for iterating over a list and generating a new list with a for loop. This means they function in the same way a for loop does, but with a different syntax.

The syntax for a list comprehension is as follows:

Example 1: Using a List Comprehension

nums = [8, 6, 4]
new_num = [num * 2 for num in nums]
print(new_num)
Example 1: Using a List Comprehension
Example 1: Using a List Comprehension

Each num in our “nums” list is multiplied by two as a result of this comprehension.

Example 2: Using a List Comprehension

We have a selection of lists of various sandwich fillings that are available at a restaurant. Our current list of lists is as follows:

foods = [
	["Onions and Tomatoes", "Hummus, Beetroot, and Lettuce"],
	["Cheese", "Egg"],
	["Ham", "Bacon", "Chicken Club", "Tuna"]
]

The first list includes vegan sandwich fillings, the second list includes vegetarian sandwich fillings; and the third list includes all meat-based sandwich fillings.

This list is combined into a single food list. A one-dimensional list is simpler to deal with than a two-dimensional list. In this list, there is no need for more than one dimension. We may use a list comprehension to delete the second dimension from our list:

food_stuffs = [
	["Tomato and Cucumber", "apples, oranges, and pineapples"],
	["Pepperoni", "Parmesan"],
	["rice", "potatoes", "wheat flour", "bread"]
]
updated_food_list = [food for sublist in food_stuffs for food in sublist]
print(updated_food_list)

This list comprehension loops through all of the lists in the Python vector “updated_food_list.” After that, each value is added to the main list. We print our list to the console once it has been produced.

Output:

Example 2: Using a List Comprehension
Example 2: Using a List Comprehension

Our list of lists has been converted to a flat list with success. Instead of three lists, all ingredients are now included inside one.

Flatten List in Python making use of a Nested for Loop

Using a nested Python for loop, we can achieve the same result. When a for loop exists inside another for loop, it is referred to as a “nested for loop.” Another way to express the following for loop is with our list comprehension:

food_stuffs = [
	["Tomato and Cucumber", "apples, oranges, and pineapples"],
	["Pepperoni", "Parmesan"],
	["rice", "potatoes", "wheat flour", "bread"]
]
updated_food_list = []
for new_list in food_stuffs:
	for food in new_list:
		updated_food_list .append(food)

print(updated_food_list)

Our code employs two for loops to iterate over each list item in each list in the original list of lists. Let’s put our code to test:

Flatten List in Python Making Use of a Nested for Loop
Flatten List in Python Making Use of a Nested for Loop

The outcome of our application is the same as the result of our list comprehension. A list comprehension is almost always preferable to a for loop. List comprehensions are simpler and easier to read than nested for loops in this situation.

Flatten List in Python using Itertools

Itertools is a Python standard library module. The latter is a tool that allows you to iterate over a set. The module includes several methods for working with iterable objects and generators.

We use the chain() form for our purposes. This method takes a list of lists as an argument and returns a flattened list.

Begin by using a Python import statement to bring the itertools module into our code:

import itertools

Then, to flatten the list, define the list of lists and use the chain() method:

food_stuffs = [
	["Tomato and Cucumber", "apples, oranges, and pineapples"],
	["Pepperoni", "Parmesan"],
	["rice", "potatoes", "wheat flour", "bread"]
]

updated_food_list = itertools.chain(*food_stuffs)

To unpack our list, we use the * symbol in our code. This transforms our list into function arguments, which the chain() method will parse.

The itertools.chain object is returned by the chain() process. We must convert this object to a list to see our flattened list. The list() method is used to accomplish this:

import itertools
food_stuffs = [
	["Tomato and Cucumber", "apples, oranges, and pineapples"],
	["Pepperoni", "Parmesan"],
	["rice", "potatoes", "wheat flour", "bread"]
]

updated_food_list = itertools.chain(*food_stuffs)
print(list(updated_food_list))
Flatten List in Python Itertools is a tool that allows you to iterate over a set
Flatten List in Python Itertools is a tool that allows you to iterate over a set

Our code has flattened our list.

Although itertools is a powerful tool for flattening lists, it is more advanced than the previous two methods.

This is because you must include itertools in your code, which adds a new dependency.
Furthermore, the chain() method requires unpacking, which can be confusing.

How to Flatten a List of Lists

In Python, the list is the most versatile data structure. A 2D list, also known as a list of lists, is a list object in which each item is a list in its own right – for example, [[1,2,3], [4,5,6], [7,8,9]].

Flattening a list of lists involves un-nesting each list item contained in the list of lists, transforming [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into [1, 2, 3, 4, 5, 6, 7, 8, 9].

Depending on the regularity and scope of the nested lists, the flattening may be done with nested for loops, list comprehensions, recursion, built-in functions, or importing libraries in Python.

Nested Lists Come in a Variety of Forms.

Since Python is a weakly typed language, you’ll come across normal and irregular lists of lists.

List of Lists regularly

Every single item in this list is a sublist, adhering to the element type’s uniformity.
[[100, 200, 300], [400, 500, 600], [800, 900]] is an example of a standard list of lists, [[100, 200, 300], [400, 500, 600], [800, 900 is a list of form list.

List of Lists in an Unusual Order (irregular)

This list’s elements are either sublists or non-list items. For example, an integer or string. Thus, there is a discrepancy in the element form. [[100, 200, 300], [400, 500], 600], where [[100, 200, 300], [400, 500], and 600 are of type list and int, respectively.

Nested for Loops to flatten a List of Lists

This is a brute-force method of creating a flat list by selecting every element from the list of lists and placing it in a 1D list.

  • Create a list of lists with dummy data and call it data.
  • Create an empty list named flat list now.
  • Iterate over the details.
  • Remove all of the items from the current list.
  • Using the list append process, add them to the flat list.
  • The outcome should be printed.

The code is simple to understand and works with both usual and irregular lists of lists, as shown below:

Example 1: Nested for Loops to Flatten a List of Lists

# flattenListUsingForLoop.py

def flattenListUsingForLoop(two_d_list):
    new_flat_list = []

    # outer list iteration

    for item in two_d_list:
        if type(item) is list:
            # If the item is of type list, do sublist iteration

            for _item in item:
                new_flat_list .append(_item)
        else:
            new_flat_list .append(item)
    return  new_flat_list

the_nested_list = [[100, 200, 300], [400, 500, 600], [800, 900]]
print('Initial List: ', the_nested_list )
print('Flattened List: ', flattenListUsingForLoop(the_nested_list ))
Example 1: Nested for Loops to Flatten a List of Lists
Example 1: Nested for Loops to Flatten a List of Lists

Example 2: Nested for Loops to Flatten a List of Lists

# initialize the initial_data and an empty list called new_flat_list
initial_data = [[100, 200, 300], [400, 500, 600], [800, 900]]

new_flat_list = []

# iterating over the initial_data
for item in initial_data:
    # add items to the flat_list
    new_flat_list  += item

# printing the resultant new_flat_list 
print(new_flat_list )
Example 2: Nested for Loops to Flatten a List of Lists
Example 2: Nested for Loops to Flatten a List of Lists

Example 3: Nested for Loops to Flatten a List of Lists

# nestedforLoops.py
original_list = [[100, 200, 300], [400, 500, 600], [800, 900]] # Original list to be flattened
flattened_list = []

for i in range(len(original_list )): #Traversing through the main list
  for j in range (len(original_list [i])): #Traversing through each sublist
    flattened_list.append(original_list [i][j]) #Appending elements into our flat_list
    
print("Original List:",original_list )
print("New Flattened List:",flattened_list)
Example 3: Nested for Loops to Flatten a List of Lists
Example 3: Nested for Loops to Flatten a List of Lists

Example 4: Nested for Loops to Flatten a List of Lists

# nestedForLoopsListOfLists.py
original_nested_list = [ [ 20, 30, 40,50], ["Twenty", "Thirty","Forty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]
new_flat_list=[]
for sublist in original_nested_list :
    for item in sublist:
        new_flat_list.append(item)
print(new_flat_list)
Example 4: Nested for Loops to Flatten a List of Lists
Example 4: Nested for Loops to Flatten a List of Lists

Using a List comprehension to flatten a list of lists

This method creates a flat list based on an existing 2D list in an elegant but less intuitive manner. The resultant result is from a single compact statement.

Example 1: Using a List Comprehension, flatten a list of lists

original_nested_list = [[100, 200, 300], [400, 500, 600], [800, 900]]
new_flattened_list = [item for sublist in original_nested_list  for item in sublist]
print('Original list: ', original_nested_list )
print('Flattened list: ', new_flattened_list )

Output:

Example 1: Using a List Comprehension, flatten a list of lists
Example 1: Using a List Comprehension, flatten a list of lists

Example 2: Using, a List Comprehension, flatten a list of lists

original_nested_list = [ [ 20, 30, 40,50], ["Twenty", "Thirty", "Forty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]
new_flattened_list=[item for sublist in original_nested_list  for item in sublist]
print(new_flattened_list)

Example 2: Using, a List Comprehension, flatten a list of lists
Example 2: Using, a List Comprehension, flatten a list of lists

Recursively flatten a list of lists

Recursively flattening the 2D list is also possible. The following code works on both usual and irregular lists of lists:

def flattenList(list_of_lists):
    if len(list_of_lists) == 0:
        return list_of_lists
    if isinstance(list_of_lists[0], list):
        return flattenList(list_of_lists[0]) + flattenList(list_of_lists[1:])
    return list_of_lists[:1] + flattenList(list_of_lists[1:])


print(flattenList([[100, 200, 300], [400, 500, 600], [800, 900], 1000]))

output:

Recursively flatten a list of lists
Recursively flatten a list of lists

Making Use of Libraries

You can also use Python libraries to help you with this. List of Lists should be flattened using functools (reduce() and iconcat()).
The iconcat() function performs the basic concatenation operation on the items of a list of lists, from left to right, to reduce it to a single list:

Example 1: Making Use of Libraries

import functools
import operator
original_list = []

# Transforming an irregular 2D list into a original one.
def transformList(nested_list):
    for ele in nested_list:
        if type(ele) is list:
            original_list.append(ele)
        else:
            original_list.append([ele])
    return original_list


irregular_list =[[100, 200, 300], [400, 500, 600], [800, 900,1000], 1100]
new_2D_list = transformList(irregular_list)
print('Original list: ', irregular_list)
print('Flattened List: ', functools.reduce(operator.iconcat, new_2D_list, []))
Example 1: Making Use of Libraries
Example 1: Making Use of Libraries

Example 2: Making Use of Libraries

import functools
import operator

original_list = [[100, 200, 300], [400, 500, 600], [800, 900]] #List to be flattened

flattened_list = functools.reduce(operator.iconcat, original_list , [])

print("Original List: ",original_list )
print("Flattened List: ",flattened_list)
Example 2: Making Use of Libraries
Example 2: Making Use of Libraries

Example 3: Making Use of Libraries

from functools import reduce
from operator import concat

original_nested_list = [ [10, 20, 30, 40], ["Ten", "Twenty", "Thirty","Forty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]
new_flat_list = reduce(concat, original_nested_list )
print(new_flat_list )
Example 3: Making Use of Libraries
Example 3: Making Use of Libraries

List of Lists should be flattened by itertools.chain()

Since it treats consecutive sequences as a single sequence by iterating through the iterable passed as the argument sequentially, this method is suitable for converting a 2-D list into a single flat list.

Example 1: Flatten List of Lists by itertools.chain()

import itertools

original_list =[[100, 200, 300], [400, 500, 600], [800, 900]] #List to undergo flattening
new_flat_list = list(itertools.chain(*original_list))

print('Original list: ', original_list)
print('Flattened list: ', new_flat_list )
List of Lists should be flattened by itertools.chain()
List of Lists should be flattened by itertools.chain()

Example 2: Flatten List of Lists by itertools.chain()

# flattenListOfListsByItertoolsChain.py
import itertools
 
if __name__ == '__main__':
 
    original_list = [[100, 200, 300], [400, 500, 600], [800, 900]]

    joined_list = list(itertools.chain.from_iterable(original_list))
    print('Original list: ', original_list)
    print('Flattened list: ', joined_list )
Example 2: Flatten List of Lists by itertools.chain()
Example 2: Flatten List of Lists by itertools.chain()

List of Lists should be flattened Using NumPy (flat () and concatenate ())

Concatenating standard 2D arrays row-wise or column-wise is one of NumPy’s most common operations. To achieve our target, we also use the flat attribute to get a 1D iterator over the list. This method, however, is relatively slow:

import numpy

original_list = [[100, 200, 300], [400, 500, 600], [800, 900]]


flattened_list = list(numpy.concatenate(original_list ).flat)

print('Original list: ', original_list)
print('Flattened list: ', flattened_list)
List of Lists should be flattened Using NumPy (flat() and concatenate())
List of Lists should be flattened Using NumPy (flat() and concatenate())

Using the built-in Functions

Flatten a list using function sum()

To flatten a list, you can use the built-in function sum().

The second argument of sum can be used to specify an initial value (). The + operation on the list will concatenate lists if you move the empty list [].

In Python, you can add a new item to a list (append, extend, insert)
Since the default value of the second statement is 0, if it is omitted, the + operation with int and list will result in an error.

Example 1: Flatten a list using function sum()

original_list = [[100, 200, 300], [400, 500, 600], [800, 900]]


flattened_list = sum(original_list, [])

print('Original list : ', original_list)
print('Flattened list: ', flattened_list)

output:

Example 1: Flatten a list using function sum()
Example 1: Flatten a list using function sum()

Applying the += operator

The += operator in Python allows you to perform list operations like concatenation. You may use the + or += operators to enter chained input as follows:

Example: Applying the += operator

# applyingPlusoperator.py

if __name__ == '__main__':
 
    original_list = [[100, 200, 300], [400, 500, 600], [800, 900]]

    joined_list = []
    for list in original_list:
        joined_list +=  list
 
    print('Original list : ', original_list)
    print('Flattened list: ', joined_list )
Example : Applying the += operator
Example: Applying the += operator

Using Lambda to flatten a list of lists

The lambda keyword can be used to describe an anonymous function. The regular/irregular list is passed to this anonymous function as an argument, and the expression is evaluated to produce a flat 1D list:

Example 1: Using Lambda to flatten a list of lists

original_list = [[100, 200, 300], [400, 500, 600], [800, 900]]


# how to use lambda arguments: expression

flattened_list = lambda original_list:[element for item in original_list for element in flattened_list(item)] if type(original_list) is list else [original_list]

print("\nOriginal list:  ", original_list)
print("\nFlattened List: ", flattened_list(original_list))
Example 1: Using Lambda to flatten a list of lists
Example 1: Using Lambda to flatten a list of lists

Example 2: Using Lambda to flatten a list of lists

from functools import reduce

original_nested_list = [ [10, 20, 30, 40], ["Ten", "Twenty", "Thirty","Forty"], [1.1,  1.0E1, 1+2j, 20.55, 3.142]]

flattened_list = reduce(lambda a,b:a+b, original_nested_list )

print(flattened_list )
Example 2: Using Lambda to flatten a list of lists
Example 2: Using Lambda to flatten a list of lists

Another choice is to add the inner lists together. The function takes two parameters: iterable, which is a list of lists, and start, which in our case is an empty list that serves as the initial flat list to which items from the inner sublists are added.

This method is convenient because it does not require any imports, but it is slower than itertools() and chain() when the number of sublists is large:

To Flatten multi-level lists

# initializing the original data and empty list
original_list = [[100, 200, 300], [400, 500, 600], [800, 900]]

flattened_list = []

# function
def flattenList(original_list ):
    # iterating over the original_list 
    for item in original_list:
        # checking for list
        if type(item) == list:
            # calling the same function with current item as new argument
            flattened_list(item)
        else:
            flattened_list .append(item)

# flattening the original list
flattenList(original_list )

# printing the flattened List
print(flattened_list )
To Flatten multi-level lists
To Flatten multi-level lists

Final Thoughts

We have discussed all the various approaches for flattening a list, including a nested for loop, a list comprehension, recursively flattening a list, using NumPy to flatten a list of lists, using Lambda to flatten a list of lists, using built-in functions, and the itertools.chain() method. In most cases, list comprehension is preferred because it is the most “Pythonic” in form.

Although nested for loops are effective, they require more code lines than a list comprehension. The itertools.chain() method is also useful, but it cannot be easy to grasp for beginners.

When Python provides all the resources, and there is a need to flatten a list, there’s typically no need to import a new library — itertools.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More