In this tutorial we’ll be explaining how to flatten 2D Lists (or Arrays) in Python. What does the term “flatten” mean though? Flattening means to reduce the dimensions of an object, in this case a list or array.
What we want, is to flatten or “collapse” a 2D array, into a 1D array. No values will be lost, and the new 1D array will contain all the values from the 2D array, including the nested ones.
If you want a real-life, practical example of where we use these techniques, check out the popular Radix Sort Algorithm. It uses the concept of storing values in a 2D list, and then flattening it into a 1D list during it’s sorting process.
Flattening 2D Lists (Arrays) in Python
Luckily, Python offers us a many different ways through which we can achieve such a task. You could even write the code for it yourself. It’s actually pretty simple if you think about it.
We’ll discuss each technique here in sequence.
1# Reduce Function
In this technique we will use the reduce function from the functools
library in Python.
from functools import reduce
list_2D = [ [1, 2, 3],
[4, 5, 6],
[7, 8],
[9] ]
print("Before: " + str(list_2D))
list_1D = reduce(lambda x, y : x + y, list_2D)
print("After: " + str(list_1D))
Output:
Before: [[1, 2, 3], [4, 5, 6], [7, 8], [9]]
After: [1, 2, 3, 4, 5, 6, 7, 8, 9]
2# Sum Function
This is also another very similar technique to the one above using the inbuilt function, sum()
.
list_2D = [ [1, 2, 3],
[4, 5, 6],
[7, 8],
[9] ]
print("Before: " + str(list_2D))
list_1D = sum(list_2D, [])
print("After: " + str(list_1D))
Output:
Before: [[1, 2, 3], [4, 5, 6], [7, 8], [9]]
After: [1, 2, 3, 4, 5, 6, 7, 8, 9]
3# Chain Function
Here we will use the chain
ability from the itertools
module.
from itertools import chain
list_2D = [ [1, 2, 3],
[4, 5, 6],
[7, 8],
[9] ]
print("Before: " + str(list_2D))
list_1D = list(chain.from_iterable(list_2D))
print("After: " + str(list_1D))
Output:
Before: [[1, 2, 3], [4, 5, 6], [7, 8], [9]]
After: [1, 2, 3, 4, 5, 6, 7, 8, 9]
4# List Comprehension
This is a very Python specific technique, called List Comprehension. Amongst it’s many uses, it can also be used to iterate over all the elements in the 2D array and add them into the 1D array.
list_2D = [ [1, 2, 3],
[4, 5, 6],
[7, 8],
[9] ]
print("Before: " + str(list_2D))
list_1D = [j for sub in list_2D for j in sub]
print("After: " + str(list_1D))
Output:
Before: [[1, 2, 3], [4, 5, 6], [7, 8], [9]]
After: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The above techniques are meant to flatten 2D arrays into 1D arrays. If you have something more than 2D, like 3D or higher, (which is pretty unlikely), you can repurpose the above techniques to work on arrays and lists of higher dimensions as well.
This marks the end of the Python, Flatten 2D arrays and lists Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.