How to make a flat list out of list of lists in Python

In this Python tutorial, I will show you how to make a flat list out of list of lists in Python. We know that a list can contain multiple elements in it. But when a list will contain elements and each element will itself be a list then the parent list will be known as Flat List.

You can also read,

Add item to a specific position in list Python Programming

Here we will learn how to take the elements of the flat list one by one using for loops.



Make a flat list out of list of lists in Python

To make a flat list out of list of list in Python we will do the following things so that you can understand it

  • We will create a list where the elements will also be list itself
  • Thereafter, We will take an empty list
  • Using nested loops ( Two for loops ) we will get each element one by one and put the elements in the empty list we just created before.

Let’s create our first list first

my_list =[[15,25,89,75],[12,89,61,81],[58,62,34,68],[78,65,95,15]]
print(my_list)

Output:

[[15, 25, 89, 75], [12, 89, 61, 81], [58, 62, 34, 68], [78, 65, 95, 15]]
Process finished with exit code 0

You can see that in my_list we have 4 elements and each of them are themselves a list.

Now we have to take these elements out one by one.

In order to do this, we will create an empty list first then using a nested for loop we will add each element to the empty list one by one.

my_list =[[15,25,89,75],[12,89,61,81],[58,62,34,68],[78,65,95,15]]
print(my_list)
my_flat_list=[]
for mini_list in my_list:
  for each_item in mini_list:
    my_flat_list.append(each_item)
print (my_flat_list)

Output:

[[15, 25, 89, 75], [12, 89, 61, 81], [58, 62, 34, 68], [78, 65, 95, 15]]
[15, 25, 89, 75, 12, 89, 61, 81, 58, 62, 34, 68, 78, 65, 95, 15]

Process finished with exit code 0

How to escape from special characters in python

Leave a Reply

Your email address will not be published. Required fields are marked *