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 with the help of the code example.

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.

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

Python program for making a flat list out of list of lists

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 loop ( Loops inside a loop ) we will get each element one by one and put the elements in the empty list.

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

2 responses to “How to make a flat list out of list of lists in Python”

  1. Eugene says:

    Good explanation, but actually bad idea for tutorial, imho. Real problem with flattening of lists or another structures it’s, you don’t now how many levels there in each items of initial list. For example, if you need flattening this: [1, [2,3,[4,5,6]],7,8,[9],10].

    Code in article good only for one specific case (which solved with one comprehension [item[i] for item in arr for i in range(len(arr))] ), and doesn’t solve general problem.

    Here example of general recursive solve of this problem:
    “`
    def flatten_lists(arr):
    if len(arr) == 0:
    return arr
    if isinstance(arr[0], list):
    return flatten(arr[0]) + flatten(arr[1:])
    return arr[:1] + flatten(arr[1:])

  2. Saruque Ahamed Mollick says:

    Thanks. We really appreciate your answer. It might help the learners

Leave a Reply

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