In your programming journey, you may have to deal with situations that involve manipulating the data. Programmers work with nested lists which are multi-dimensional. The process of converting them to a one-dimensional list is called flattening of lists which is beneficial for handling the data in Python. Python offers a variety of methods to flatten a list of lists in Python, which are listed below:
- Approach 1: Flatten a List of Lists Using a Nested Loop
- Approach 2: Flatten a List of Lists Using List Comprehension
- Approach 3: Flatten a List of Lists Using the Chain Method From itertools
- Approach 4: Flatten a List of Lists Using chain.from_iterable From itertools
- Approach 5: Flatten a List of Lists Using Sum
- Approach 6: Flatten a List of Lists Using functools.reduce
- Approach 7: Flatten a List of Lists Using numpy.concatenate
- Approach 8: Flatten a List of Lists Using numpy.array
How to Flatten a List of Lists in Python?
A list of lists can be called a nested list and it is multidimentional. One usual operation is to convert this multidimensional list to a single dimension list which will be called a flat list. The following visual illustration demonstrates the difference between a nested and a flat list:
Let us discuss some examples for a better understanding of this concept.
Approach 1: Flatten a List of Lists Using a Nested Loop
Using a for loop is the most suitable/easiest method to flatten a list. An outer for loop iterates over the nested list while an inner for loop iterates through each element of the sub-lists. The following code shows how a nested list can be flattened using a for loop:
nes_lst = [[4, 4, 5], [64, 37, 34], [74], [48, 59]]
flt_lst = []
for sub_lst in nes_lst:
for i in sub_lst:
flt_lst.append(i)
print(flt_lst)
In the above code,
- A nested list “nes_lst” is defined which takes different lists as inputs.
- A variable flat list is initialized with an empty list that will store the flattened one-dimensional list.
- The outer loop iterates over each sub_lst in the “nst_lst” and each element i is operated through sub_lst.
- Each element i is appended to the flt_lst using the append method.
- After all the iterations have been completed. The flt_lst will contain elements of the nested loop in the form of a flattened list.
- The flattened list flt_lst is then printed.
Output
The following output displays how a nested loop can be flattened using a for loop:
Approach 2: Flatten a List of Lists Using List Comprehension
The next method to flatten a list is by using list comprehension. This method is speedy as compared to using the nested for loops. The following code displays how a nested list can be flattened using list comprehension:
def flat_list(nst_lst):
return [i for row in nst_lst for i in row]
nst_lst = [
[3, 43, 58, 73],
[45, 54, 22, 84],
[69, 47, 63, 51],
[13, 22, 24, 25],
]
print(flat_list(nst_lst))
In the above code,
- A function flat_list is defined that takes the argument nst_lsr.
- Two loops are defined inside a list comprehension. One loop iterates through each sublist in the nst_lst. The nested loop iterates through each element i within each sublist row.
- The return statement gives back the flattened list.
- The flat_list function is called on the nested list which is then printed.
Output
The following output displays how a nested list can be flattened using list comprehension:
Approach 3: Flatten a List of Lists Using the Chain Method From itertools
The standard Python library itertools gives the chain function to flatten a list. The list is taken as an argument and * unpacks the elements/items of the list. The resulting value is changed to a list by utilizing a list() function. The following code shows how a nested list can be fattened using the chain method from itertools:
import itertools
nst_lst = [[65, 44, 55], [4, 7, 64], [40], [478, 579]]
flt_lst = itertools.chain(*nst_lst)
flt_lst = list(flt_lst)
print(flt_lst)
In the above code,
- The library itertools is imported.
- A nested list is defined.
- *nst_lst unpacks all the elements inside the nested list.*nst_lst unpacks all the elements of the nested loop and gives it as a separate argument to the “itertools.chain()” method which takes multiple iterators as an argument and returns a single iterator which is stored in the variable flt_lst.
- The flat list is then converted to a list using the list function and is printed to display the flattened list.
Output
The following output displays how a nested list can be flattened using the chain method from the itertools:
Approach 4: Flatten a List of Lists Using chain.from_iterable From itertools
It is similar to the chain method but it takes the nested loop as an argument. All the elements inside the nested loop are iterable. It returns a flattened list. The following code shows a list of lists that can be flattened using the itertools.chain.from_iterable(nested_list):
import itertools
nst_lst = [[5, 4, 5], [4, 7, 64], [4], [48, 59]]
flt_lst = itertools.chain.from_iterable(nst_lst)
flt_lst = list(flt_lst)
print(flt_lst)
In the above code,
- The itertools library is Imported.
- A nested list is defined.
- The nested list nst_lst is given to the method itertools.chain.from_iterable which flattens the list and returns an iterator.
- The returned iterator is converted to a list using list() and the flattened list is then printed.
Output
The following output displays how a nested list can be flattened using chain.from_iterable from the itertools:
Approach 5: Flatten a List of Lists Using Sum
The nested list can also be flattened using the sum() function although not many programmers appreciate it due to its readability. Here is a code that uses the sum() function to flatten a list:
def flat_list(nst_lst):
return sum(nst_lst, [])
nst_lst = [
[3, 43, 58, 73],
[45, 54, 22, 84],
[69, 47, 63, 51],
[13, 22, 24, 25],
]
print(flat_list(nst_lst))
In the above code,
- A function flat_list is defined that takes nst_lst and flattens the nested list.
- The sum function concatenates the sublists inside the nested list where an empty list [] is provided as an initial argument.
- The function flat_list is called on the nst_lst which returns a flattened list.
Output
The following output displays how a nested list can be flattened using the sum function:
Approach 6: Flatten a List of Lists Using functools.reduce
The reduce function belongs to Python’s functional programming tool kit. Two arguments are provided to the function where the function is utilized to the elements of the iterable. The following code shows how a nested list can be flattened in Python using functools.reduce:
from functools import reduce
nst_lst = [[4, 86, 65], [02, 34, 86], [44], [4859]]
flt_lst = reduce(lambda a, b: a+b, nst_lst)
print(flt_lst)
In the above code,
- From the functools module reduce is imported.
- The nested list is defined which contains lists of integers.
- The reduce function flattens the nested list while taking a function and an iterable as an argument.
- The lambda function concatenates the two lists a and b.
- The flattened list will then be printed.
Output
The following output displays how a nested list can be flattened using the functools.reduce method:
Approach 7: Flatten a List of Lists Using numpy.concatenate
The numpy.concatenate function is taken from the NumPy library and returns a single iterator which in this case is a flattened list. The following code shows a nested list can be flattened using numpy.concatenate:
import numpy
nst_lst = [[4, 6, 5], [2, 54, 36], [84], [3359]]
flt_lst = numpy.concatenate(nst_lst)
print(flt_lst)
In the above code,
- The NumPy module is imported.
- A nested list nst_lst is defined.
- The numpy.concatenate concatenates all the nested elements into a NumPy array which is converted to a list using the list() function.
- The flattened list is then printed.
Output
The following output displays how a nested list can be flattened using NumPy.concatenate:
Approach 8: Flatten a List of Lists Using numpy.array
The numpy arrays have a flat function that returns a single flattened array but it only works if the sublists are of equal length. The resulting iterator is then converted/transformed to a list. Here is a code that shows how a nested list can be flattened in Python using np.array().flat function:
import numpy as np
nst_lst = [[5, 56, 45], [42, 45, 56]]
flt_lst = list(np.array(nst_lst).flat)
print(flt_lst)
In the above code,
- The NumPy module is imported.
- A nested list nst_lst is defined.
- np.array converts the nested list into a NumPy array.
- The flat function returns the flat iterator of the nested elements.
- The flattened elements inside the array are converted to a list using the list function.
- The flattened list is then printed.
Output
The following output displays how a nested list can be flattened into a one-dimensional list using np.array and flat function:
That’s all you need to know about flattening a list of lists in Python.
Conclusion
A nested list in Python can be flattened by using functions such as sum, functools.reduce, or libraries like itertools and NumPy. Converting a nested list into a flattened list is helpful in data manipulation, machine learning, and more. This article has discussed different methods to convert a nested list into a flattened list and explains each method with an example.