Different Techniques to Flatten a List of Lists in Python

This article will teach you how to flatten a list of lists in Python using practical examples and code.

Before we begin, we’ll go over what Python is, what a list is, and what the purpose of flattening a list is?

What is Python?

Python is a general-purpose, high-level, and interpreted programming language. Python was written and released in 1991 by Guido van Rossum. Python’s readability, simplicity, and versatility make it a popular choice for a wide range of applications. Here are some of Python’s important qualities and features:

  • Language Readability and Clean Syntax at the Highest Level.
  • Compatibility Across Platforms.
  • Objective-Oriented Programming (OOP). Extensive Standard Library.
  • Large Third-Party Library Ecosystem.
  • Versatility.
  • Community and Help.
  • It is free to use.

What is List in Python?

A Python list is a collection of ordered and changeable elements. Lists are written in square brackets, with commas between the elements. For instance, [1, 2, 3, 4]. They are a valuable data type because they allow you to store and retrieve numerous values in a single structure.

I hope this clarifies what a list is in Python. We will now go to the flattening list.

Purpose of Flattening a List:

Flattening a list of lists means storing all of the elements from the nested lists inside the parent list. A nested list is a list that is contained within another list or data structure. Flattening is also effective for reducing the time and space complexity of your program.

The following Python methods will be used in this article to flatten a list of lists:

  • Using the for loop method, flatten a list of lists.
  • To flatten a list of lists, use the list comprehension approach.
  • Using the NumPy library to flatten lists.
  • The sum() function can be used to flatten a list of lists.
  • To flatten the list of lists, we can also utilize itertools’ chain function.
  • A list of lists can also be flattened using the lambda and reduce functions.

 

1. Using for loop:


# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Create a list of lists by combining the two lists
listoflists = [list1,list2]

# Initialize an empty list to store the flattened result
flattenlist = []

# Iterate through each sublist in the listoflists
for sublist in listoflists:

    	# Iterate through each element in the current sublist                                                  
	for x in sublist:

		# Append each element to the flatten list
		flattenlist.append(x)

# Print the final flattened list
print(flattenlist)

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

Code Explanation:

  1. list1  and list2 are two independent lists having integer elements.
  2. listoflists is formed as a list that contains list1 and list2, producing a list of lists.
  3. An empty flattenlist is created to hold the flattened result.
  4. The outer loop iterates through each sublist in the list of lists.
  5. The inner loop iterates through each element x in the current sublist.
  6. Each element x is appended to the flattenlist.
  7. The final flattened list is printed after both loops have been completed. In this scenario, it will print [1, 2, 3, 4, 5, 6].

2. Using List Comprehension:

List comprehensions are a quick and simple method for flattening a list of lists. 


# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Create a list of lists by combining the two lists
listoflists = [list1,list2]

# Initialize an empty list to store the flattened result
flattenlist = []

# Use a list comprehension to flatten the list
# The expression [x for sublist in listoflists for x in sublist] iterate through each sublist in listoflists
# and for each element x in the currnt sublist, it appends x to the flattened list.
flattenlist = [x for sublist in listoflists for x in 	sublist]

# Print the final flattened list
print(flattenlist)

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

Code Explanation:

  1. list1 and list2 are two separate lists with integer elements.
  2. listoflists is created as a list containing list1 and list2, forming a list of lists.
  3. The list comprehension [x for sublist in listoflists for x in sublist] replaces the nested loops from the previous code.
  4. It iterates through each sublist in listoflists and, for each element x in the current sublist, appends x to the flattenlist.
  5. After the list comprehension is completes, the final flattened list is printed. In this case, it will print [1, 2, 3, 4, 5, 6].

3. Using NumPy:


# Import the NumPy library with the alias np
import numpy as np

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Create a list of lists by combining the two lists
listoflists = [list1,list2]
		
# Use NumPy flatten method to flatten the listoflists
# Convert the list of lists to a NumPy array using np.array and then flatten it
flattenlist = np.array(listoflists).flatten()

#Print the final flattened NumPy array
print(flattenlist)

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

Code Explanation:

  1. import numpy as np: Imports the NumPy library with the alias np for convenience.
  2. list1 and list2 are two separate lists with integer elements.
  3. listoflists is created as a list containing list1 and list2, forming a list of lists.
  4. np.array(listoflists) converts the list of lists into a NumPy array.
  5. flatten() is a method provided by NumPy to flatten multi-dimensional arrays into a one-dimensional array.
  6. The flattened result is stored in the flattenlist.
  7. Finally, the flattened NumPy array is printed. In this case, it will print [1, 2, 3, 4, 5, 6].

4. Using build-in sum() function:


# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Create a list of lists by combining the two lists
listoflists = [list1,list2]

# Use the sum function to flatten the list of lists
# The second argument to sum is an empty list, acting as the starting point for the summation.
# The elements of each sublist are successively added to this empty list, effectively flattening the list.
flattenlist = sum(listoflists,[])

# Print the final flattened list.
print(flattenlist)

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


Code Explanation:

  1. list1 and list2 are two separate lists with integer elements.
  2. listoflists is created as a list containing list1 and list2, forming a list of lists.
  3. sum(listoflists, []) uses the sum function to concatenate the sublists in listoflists.
  4. The second argument to sum is an empty list ([]), which serves as the initial value for the summation.
  5. The elements of each sublist are successively added to this empty list, effectively flattening the list.
  6. The final flattened list is stored in the variable flattenlist.
  7. Finally, the flattened list is printed. In this case, it will print [1, 2, 3, 4, 5, 6].

 

5. Using Chain function from itertools:


# Import the chain function form the itertool module
from itertools import chain

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Create a list of lists by combining the two lists
listoflists = [list1,list2]

# Use the chain function to flatten the list of lists
# The *listoflists synax is used to unpack the list of lists and pass them as arguments to the chain function
# The chain function then concatenates the sublists into a single iterable. 
flattenlist = list(chain(*listoflists))
 
# Print the final flattened list
print(flattenlist)

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


Code Explanation:

  1. from itertools import chain: Imports the chain function from the itertools module.
  2. list1 and list2 are two separate lists with integer elements.
  3. listoflists is created as a list containing list1 and list2, forming a list of lists.
  4. chain(*listoflists) uses the chain function to concatenate the sublists in listoflists.
  5. The *listoflists syntax is used to unpack the list of lists and pass them as arguments to the chain function.
  6. The chain function then concatenates the sublists into a single iterable.
  7. list(chain(*listoflists)) converts the iterable into a list, effectively flattening it.
  8. The final flattened list is stored in the variable flattenlist.
  9. Finally, the flattened list is printed. In this case, it will print [1, 2, 3, 4, 5, 6].

6. Using Lambda and reduce:

In this method, we use lambda function for addition and the reduce function to apply that to all the elements of the sublist.


# Import the reduce function form the functools module
from functools import reduce

# Define two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# Create a list of lists by combining the two lists
listoflists = [list1,list2]

# Use reduce and a lambda function to flatten the list of lists
# The lambda function takes two arguments (x and y) and concatenate them. 
# The reduce function successively applies the lambda function to the elements of the listoflists, effectively flattening the list. 
flattenlist = list(reduce(lambda x,y: x+y,listoflists))
 
# Print the final flattened list
print(flattenlist)

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


Code Explanation:

  1. from functools import reduce: Imports the reduce function from the functools module.
  2. list1 and list2 are two separate lists with integer elements.
  3. listoflists is created as a list containing list1 and list2, forming a list of lists.
  4. reduce(lambda x, y: x + y, listoflists) uses the reduce function to successively apply the lambda function to the elements of listoflists.
  5. The lambda function takes two arguments (x and y) and concatenates them.
  6. The result is a single list obtained by concatenating all the sublists in listoflists.
  7. list(reduce(lambda x, y: x + y, listoflists)) converts the result into a list, effectively flattening it.
  8. The final flattened list is stored in the variable flattenlist.
  9. Finally, the flattened list is printed. In this case, it will print [1, 2, 3, 4, 5, 6].

 

CONCLUSION:

Mastering list flattening in Python is crucial for programmers. Whether using recursion, iteration, or Python’s built-in functions, seamlessly transforming nested lists enhances code readability and improves data manipulation efficiency. Proficiency in flattening lists leads to streamlined algorithms, concise code, and demonstrates the elegance achievable in Python programming.

Author Name : Mahalakshmi K
Position : Data Analyst Aspirant,
                  Aruvi Institute of Learning

Similar Posts

Leave a Reply

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