You are currently viewing Python Flatten List of Lists with Examples

Have you wondered to make a flattened list from a list of lists in Python? Flattening is required to simplify data processing and analysis. In Python, there are several methods to flatten the list. These include using nested for loops, list comprehension, reduce(), chain(), sum(), and recursive solutions. In this article, we will explain these methods with examples.

Advertisements

Methods to Flatten the List in Python

  1. Flatten list using for loop
  2. Flatten list using List Comprehension
  3. Specifying lambda expression within the reduce() method
  4. Specifying operator.concat within the reduce() method
  5. Flatten list using fitertools.chain()
  6. Using numpy.concatenate().flat method
  7. Using the sum() function.

1. Quick Examples of Flatten List

The following examples demonstrate the different approaches to flattening a list of lists into a list in Python. These examples provide a quick overview of the methods we will explore in detail.


from functools import reduce
from itertools import chain
import numpy as np

# Create list of list
lst = [[1, 2, 3], [4, 5,4], [6, 8, 9]]

# Nested for loops method
flat_list = []
for sublist in lst:
    for item in sublist:
        flat_list.append(item)
print("Nested for loops method: ", flat_list)

# reduce() method
flat_list = reduce(lambda x, y: x+y, lst)
print("reduce() method: ", flat_list)

# Using List Comprehension
print("Flatten List: ",[j for i in lst for j in i])

# chain() method
flat_list = list(chain(*lst))
print("chain() method: ", flat_list)

# sum() method
flat_list = sum(lst, [])
print("sum() method: ", flat_list)

# numpy library's flatten() method
flat_list = np.array(lst).flatten().tolist()
print("numpy flatten() method: ", flat_list)

2. Flatten List using Nested For Loop

Using nested for loop is one of the simplest and most straightforward ways to flatten a list of lists in Python. The idea is to iterate over each sub-list in the main list, and then iterate over each element in the sub-list and append it to a new list.

In the below example, we have a list of sub-lists containing integers. We create an empty list flattened_list to store the flattened elements. The resulting list is a flattened version of the input list, with all elements at the same level.


# Create list of list
my_list = [['C', 'Lua'], ['Perl', 'D'], ['Go', 'R']]

# Create a new list to store flattened elements
flattened_list = []

# Iterate over each list in the main list
for sub_list in my_list:
    # Iterate over each element in the sub-list
    for item in sub_list:
        # Append the item to the flattened list
        flattened_list.append(item)

print(flattened_list)  

# Output:
# ['C', 'Lua', 'Perl', 'D', 'Go', 'R']

The good Point in the nested for-loop method works with irregular-shaped lists as well.

3. Using List Comprehension to Flatten List

To flatten a list of lists use list comprehension in Python, we can use a nested for loop within the comprehension. The result is a one-liner that is both concise and efficient.

It allows you to define a new list in a single line of code, without the need for explicit loops. In the following example, we create a new list called flattened_list using list comprehension.


# Using list comprehension to flatten the list
flattened_list = [item for sub_list in my_list for item in sub_list]
print(flattened_list)  

# Output: 
# ['C', 'Lua', 'Perl', 'D', 'Go', 'R']

4. reduce() to Make Flat List from Nested Lists

The reduce() function from the functools module can also be used to flatten a list of lists. The reduce() function applies a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

Example using the my_list we defined earlier:


# Import reduce from functools module
from functools import reduce

# Using reduce() to flatten the list
flattened_list = reduce(lambda x, y: x + y if isinstance(y, list) else x + [y], my_list)
print(flattened_list)  

# Output: 
# ['C', 'Lua', 'Perl', 'D', 'Go', 'R']

5. chain() – Flat List from List of Lists

To use chain() to flatten a list of lists in Python, we first need to import the chain() function from the itertools module. We can then pass the list of lists as arguments to the chain() function. The chain() function will concatenate the sublists and return a flattened list.


from itertools import chain

# Using chain() to flatten the list
flattened_list = list(chain(*my_list))

print(flattened_list)  
# output: ['C', 'Lua', 'Perl', 'D', 'Go', 'R']

6. sum() – List of List to Flat List

The sum() function in Python is primarily used to add up a sequence of numbers, but it can also be used to concatenate a sequence of lists or strings. When used with an empty list as the second argument, the sum() function can be used to flatten a list of lists.


flattened_list = sum(my_list, [])
print(flattened_list)

# Output: 
# ['C', 'Lua', 'Perl', 'D', 'Go', 'R']

7. numpy flatten() – To Flat Nested Lists

numpy is a powerful library for scientific computing in Python. It provides a method called flatten() that can be used to flatten a nested list.

To use flatten(), we first need to convert the list of lists into a numpy array using the numpy.array() method. We can then use the flatten() method on the resulting array to get a flat list.


# Import Numpy
import numpy as np

# Flat Nested Lists
flat_list = np.array(my_list).flatten().tolist()
print(flat_list)

8. pandas stack() – To Flat List of List

The pandas library provides a convenient method called stack() to flatten a list of lists. The stack() method essentially takes a DataFrame or a Series with a MultiIndex and returns a reshaped DataFrame or Series with a simple index. In this case, we can create a DataFrame from our list of lists and then use the stack() method to flatten it.


import pandas as pd

# Create a DataFrame from the list of lists
df = pd.DataFrame(my_list)

# Use the stack() method to flatten the DataFrame
flattened = df.stack().tolist()

print(flattened)

9. Handling Irregular Nested Lists

Handling irregular nested lists can be a bit more challenging since the number of levels in the list hierarchy can vary between sub-lists. However, several of the methods we discussed, like list comprehension and reduce(), can still be applied to these types of lists.

Except the stack() method of pandas library, all other methods will give you an error, if you have a list that contains both individual items and a list. So you need to make sure you use them with caution.

With these methods and tools, you can easily work with and manipulate nested lists of varying shapes and sizes.

10. Summary and Conclusion

We learned different methods to make a flatten list from a list of lists in Python. We covered using nested for loops, list comprehension, reduce(), chain(), sum(), recursive solution, numpy’s flatten() method, and pandas’ stack() method. Leave a comment if you have any questions.

Happy coding!

References