Sling Academy
Home/Python/Python: How to Flatten a Nested List (3 Approaches)

Python: How to Flatten a Nested List (3 Approaches)

Last updated: June 13, 2023

When writing code in Python, there might be cases where you want to flatten a nested list in order to make it easier to access, modify, or iterate over the elements or to perform operations that require a one-dimensional list. This concise, example-based article will walk you through a couple of different ways to flatten a given nested list. We’ll also discuss the performance of each approach so you can get an understanding of how fast and efficient it is.

Using list comprehension

You can use list comprehension to generate a new list from an iterable or a range of values and apply a function or an expression to each element. You can also nest list comprehensions inside each other to flatten nested lists.

Example:

# Creating a nested list
nested_list = [[1, 2, 3], ['A', 'B', 'C'], [True, False, None]]

# Flattening the nested list using list comprehension
flat_list = [item for sublist in nested_list for item in sublist]

# Printing the flattened list
print(flat_list)

Output:

[1, 2, 3, 'A', 'B', 'C', True, False, None]

Performance: This method has a time complexity of O(n), where n is the number of elements in the nested list. It also has a space complexity of O(n), since it creates a new list object.

Using loops

You can use loops to iterate over the elements of your nested list and append them to a new list. Both for loops and while loops are fine.

This method is easy to read and write, and allows you to flatten nested lists of any size and shape. You can also use the break and continue statements to control the flow of the loop. The downsides are that this approach can be tedious and verbose compared to list comprehension. It also requires you to create an empty list before the loop and append each element manually.

Example:

# Creating a nested list
nested_list = [[1, 2, 3], ['A', 'B', 'C'], [True, False, None]]

# Flattening the nested list using loops
flat_list = []
for sublist in nested_list:
    for item in sublist:
        flat_list.append(item)

print(flat_list)

Output:

[1, 2, 3, 'A', 'B', 'C', True, False, None]

Performance: This approach has a similar time and space complexity as using list comprehension since it essentially does the same thing under the hood. However, it may be slightly slower due to the overhead of calling the append() method.

Using the itertools.chain() function

The itertools.chain() function takes one or more iterables as arguments and returns an iterator that yields all their elements one by one. It is very convenient and efficient if you need to flatten a nested list that contains only iterables (such as lists, tuples, sets, etc.). It also avoids creating intermediate lists and copies each element only once. The result is an iterator object, not a list object (you can use list() for conversion).

Example:

# Importing the itertools module
import itertools

nested_list = [[1, 2, 3], ['A', 'B', 'C'], [True, False, None]]

# Flattening the nested list using itertools.chain
flat_list = list(itertools.chain(*nested_list))

print(flat_list)

Output:

[1, 2, 3, 'A', 'B', 'C', True, False, None]

Performance: This method has a time complexity of O(n). It also has a space complexity of O(n) since it creates a new list object. However, it may be faster or more memory-efficient than using list comprehension or loops, depending on the implementation and optimization of itertools.

Conclusion

We’ve covered the three best techniques to turn a nested list into a one-dimensional list without using third-party libraries. Their performances are not much different, so you can choose the one that fits your preferences to go with. Happy coding & have a nice day!

Next Article: Cloning a List in Python (Deep Copy & Shallow Copy)

Previous Article: Working with Nested Lists in Python (5 Examples)

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types
  • Python: Typing a function with *args and **kwargs