How do I make a flat list out of a list of lists in Python?
|Often, we end with a list of lists while programming and need to process every element or need a flat list out of it. in this Python example we will discuss some of the ways to make a flat list out of a list of lists in Python.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Using nested loops
One way to flatten a list of lists is to use nested loops. You can iterate over each element of the outer list, and for each element, iterate over its sub-list and append each item to a new list.
Now let’s implement a program to make a flat list out of a list of lists in Python
nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] flat_list = [] for sublist in nested_list: for item in sublist: flat_list.append(item) print(flat_list)
Output [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Using list comprehension
The same can be achieved via list comprehension i.e. flatten out list in a single statement.
nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] flat_list = [item for sublist in nested_list for item in sublist] print(flat_list)
Output [1, 2, 3, 4, 5, 6, 7, 8, 9]
3. Using itertools.chain
The itertools
module in Python provides a chain()
function that takes multiple iterables
as arguments and returns a single iterable that iterates over each item of the input iterables
.
Here is the example.
import itertools nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] flat_list = list(itertools.chain(*nested_list)) print(flat_list)
Output [1, 2, 3, 4, 5, 6, 7, 8, 9]
4. Using the functools.reduce() function
The reduce() function in Python’s functools module takes a function and a sequence as arguments and applies the function cumulatively to the items of the sequence, from left to right. Here is the code.
import functools nested_list = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] flat_list = functools.reduce(lambda x, y: x+y, nested_list) print(flat_list)
Output [1, 2, 3, 4, 5, 6, 7, 8, 9]
5. Conclusion
In this Python example, we discussed multiple ways to make a flat list out of a list of lists in Python.
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?