In your quest to learn python programming, you might have come across the fact that python does not have hard-coded variables. But there are certain data structures that do exist in python. These data structures are lists, dictionaries, tuples, and sets. Together they form a very strong method of maintaining and accessing data in the memory.
So, in this article, we will focus on lists and how to flatten a list of lists in python. We will also learn what is a list, a list of lists and why we need to flatten it. Then, we will move into methods to flatten it with source code.
What are Lists?
A Python list is a collection of items that are ordered and changeable. Lists are written with square brackets and the items are separated by commas. They are a useful data type because they allow you to store multiple values in a single structure and access them efficiently.
Lists are an essential data type in many python programming projects. They are versatile and can be used to store any type of data, from simple values like integers and strings to more complex data structures like dictionaries and objects.
Here is an example:
# create a list of integers numbers = [1, 2, 3, 4, 5] # create a list of strings words = ['apple', 'banana', 'cherry'] # create a list of mixed data types mixed = [1, 'apple', 3.14, True]
What is a list of lists?
We just saw what lists are in python. In layman's terms, lists are a collection of items under one name and you can access these items as well as change them. But what if you have multiple lists and now you want an easier method to access all of them?
Let us say for example you have 100 lists that you need to store. It would be a tedious task if you had to remember all 100 of them by their original names.
An easier method to this is creating a new list that stores all the other lists inside it. That way you can use the index to access any of the 100 lists that you want. Such a list that contains other lists is called a list of lists.
lis1 = [1,2] lis2 = [3,4,5] listoflists = [lis1,lis2] print(listoflists)
Why do we need to flatten a list of lists?
Let us revisit our earlier example. We have a new list now that stores 100 other lists inside it. Let us say we have to access an element that is stored in one of the 100 lists.
How intensive would it be to go through all the lists that are stored in our new list? What if we could have all the elements that are present inside all the 100 lists in one place? You can do this by an operation that is called flattening.
Flattening a list of lists refers to storing all the elements that are present in the nested lists inside the parent list. A nested list is a list that is inside another list or any other data structure. Flattening can also be useful if you want to reduce the time and space complexity of your program. This is because it is easier to access one list than to access one nested list.
05 Methods to Flatten a List of Lists
Now that we know the reason that we might need to flatten a list, let us have a look at the methods that we can use to do so. There are 5 methods that we can use to flatten a list. Here we will depict the methods in order of their ease. Therefore the first one is the easiest method, followed by the second, and so on.
1) Using List Comprehension
List comprehensions are a concise way to create a list using a single line of code. They are commonly used to apply a transformation to a sequence of items and create a new list with the transformed items.
lis1 = [1,2] lis2 = [3,4,5] listoflists = [lis1,lis2] flattenlist = [x for sublist in listoflists for x in sublist] print(flattenlist)
In this method, the variable x is selected from a sublist that is selected from the main list that contains all the other lists.
2) Using two for loops
We can implement the above-discussed list comprehension using two for loops. This is basically expanding the list comprehension. The source code is given below:
lis1 = [1,2] lis2 = [3,4,5] listoflists = [lis1,lis2] flattenlist =  for sublist in listoflists: for x in sublist: flattenlist.append(x) print(flattenlist)
Here again, we first select a sublist from the main list of lists, and then we select each element in the sublist and add it to the main list.
3) Using the chain function from itertools
The chain function will take a list of iterables (all lists, tuples, dictionaries, and sets are considered iterables) and will return a new iterable with all the elements it came across in the list given to it.
from itertools import chain lis1 = [1,2] lis2 = [3,4,5] listoflists = [lis1,lis2] flattenlist = list(chain(*listoflists)) print(flattenlist)
In this code, the chain function takes the list of lists, visits each sublist, and creates a new list that has all the elements that it came across in the sublists.
4) Sum function
The sum function can be used to find not just the sum of a list, but also to flatten a list of lists. The sum function takes a second argument called “start”. When an empty list is passed as an argument to sum it adds all the elements of the different sublists that are part of the list that is passed as the first argument. The code to use this method is here:
lis1 = [1,2] lis2 = [3,4,5] listoflists = [lis1,lis2] flattenlist = sum(listoflists,) print(flattenlist)
5) Lambda and reduce
In this code, we use the lambda function for addition, and the reduce function to apply that to all the elements of the sublist. What this does is, it takes all the elements of one sublist and joins it with all the elements of the second list. Then it takes the result and joins it with the third sublist. This repeats until all the elements of the sublists are combined to form one list.
from functools import reduce lis1 = [1,2] lis2 = [3,4,5] listoflists = [lis1,lis2] flattenlist = list(reduce(lambda x,y: x+y,listoflists)) print(flattenlist)
Also, learn how to partition a list in python.
We have learned that lists are created to handle all elements using one name. Many lists can be stored under one list to provide easier access. So, now you know various methods to flatten a list of lists in python.