How to Flatten a List of Lists in Python?

How to Flatten a List of Lists in Python?

Answer: Flattening the list can be done by a Built-in tool, standard library, Numpy module, or lambda function.

A flat list is a type of list that doesn’t contain any nested list. In Python, there are multiple methods to make a flat list out of a list of lists. Let’s explore these methods to make a flat list out of list of lists.

Table of Contents:

Methods to Flatten a List of Lists in Python

Python provides various built-in methods to flatten a list of lists. Following are some of these methods explained with the help of examples:

Method 1: Using Numpy flatten() method to Flatten a List of Lists in Python

This works only when the list inside the nested list is of the same length. We should start by converting the list into a Numpy array and then using the flatten() function to get the flat list.

Example:

# import numpy

import numpy as np

# nested list

list_a = [["samsung", "LG"], ["Apple", "VIVO"]]

# covert as numpy array

array = np.array(list_a)

# create 1-D array

flat_array = array.flatten()

# convert back to list

list_b = flat_array.tolist()

print(list_b)

Output:

Flatten a List of Lists in Python Output

Method 2: Using Numpy concatenate() method to Flatten a List of Lists in Python

One of the efficient ways to flatten lists is by concatenating them into a single list. It is not mandatory to have the same-length nested lists to perform concatenation.

Example:

import numpy as np

# Given a nested list

nested_list = [["x", "y", "z"], ["a", "b"]]

# flatten the list

flat_list = np.concatenate(nested_list).tolist()

print(flat_list)

Output:

Flatten a List of Lists in Python Output

Method 3: Using Loops to Flatten a List of Lists in Python

Start with creating the empty list, use a for loop to iterate over the main list and another nested for loop to iterate over the elements in the main list. And end with returning the flattened list.

Example:

# nested list

list_a = [["red", "green", "blue"], ["yellow", "pink"], ["white"], ["black", "purple"]]

# empty list

list_b = []

# nested for loop to get flattened list

for sublist in list_a:

  for element in sublist:

    list_b.append(element)

print(list_b)

Output:

Flatten a List of Lists in Python Output

Method 4: Using Chain() method to Flatten a List of Lists in Python

It is the standard library that is used to flatten lists. It is the terminating operator that gets the chain of iterable input and returns the single iterable output. i.e. it gets the group of iterable inputs at once and then produces the flattened output. In which the output usage is not direct it needs to be converted to the iterable.

Example:

# import module

import itertools

# nested list

list_a = [["wed", "tue", "mon"], ["sat", "sun"]]

# iterable chain

list_b = itertools.chain(*list_a)

list_b  = list(list_b)

print(list_b)

Output:   

method to Flatten a List of Lists in Python Output

Method 5: Using Chain.from_iterable() method to Flatten a List of Lists

It is one of the terminating operators where it takes a single iterable as the argument and the input that we provide must be iterable to get the flattened output.

Example:

# import module
import itertools

# nested list
nested_list = [["may", "June"], ["July", "august"]]

# printing flattened list
print(list(itertools.chain.from_iterable(nested_list)))

Output:

iterable() method to Flatten a List of Lists Output

Method 6: Using Sum() method to Flatten a List of Lists in Python

It is a built-in function and it is used to add a sequence of numbers along with it we can also concatenate the string and list. By adding the empty list as the second argument we get the flattened list.

Example:

list_1 = [[100], [200, 300], [400]]

list_2 = sum(list_1, [])

print(list_2)

Output:

Sum() method to Flatten a List of Lists in Python Output

Method 7: Using reduce() method to Flatten a List of Lists in Python

It operates by the repetition of the concatenation process. This functions by applying two arguments together from left to right and producing the output in flattened value.

Example:

# import module

from functools import reduce

import operator

# nested list

list_a = [["sun", "moon"], ["star"], ["planet"]]

# flatten list by reduce()

list_b = reduce(operator.concat, list_a)

print(list_b)

Output:

reduce() method to Flatten a List of Lists in Python

Method 8: Using lambda function to Flatten a List of Lists in Python

You can get the flat list by passing the irregular list to this function.’lambda’ keyword is used to obtain the flat 1-D list.

Example:

nested_list = [['Welcome'], ['To'], ['Intellipaat']]

# Using lambda keyword

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

print( flat_list(nested_list))

Output:

Using lambda function to Flatten a List of Lists in Python

Method 9: Using the List comprehension method to Flatten a List of Lists in Python

We loop over each sublist in the nested list and each item in the sublist using list comprehension. The flattened list is then returned.

Example:

def flatten_list(nested_list):
   
return [item for sublist in nested_list for item in sublist]

nested_list = [["Welcome"],
["To"], ["Intellipaat"]]

flat_list = flatten_list(nested_list)

print(flat_list)

Output:

Using lambda function to Flatten a List of Lists in Python

Conclusion

Numpy flatten() works when the nested list is of the same length, numpy concatenate() is used to flatten the list, even if they are also not the same length. Chain() gets the group of iterable inputs at once and then produces the flattened output. The above-mentioned ways are used to flatten the list from the nested list.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner