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!