/  Technology   /  How to make a flat list out of a list of lists in Python? – Part 1
How to make a flat list out of a list of lists in python

How to make a flat list out of a list of lists in Python? – Part 1

 

A list of lists is generally referred to as the 2D representation of arrays, where the elements in them are lists. Now, flattening is a process that converts these 2D lists to 1D lists, in other words, a list of lists to a flat list. 

 

This process can be achieved by various approaches. In this part, we’ll discuss 

  • Using the append() list method
  • Using Nested Loop
  • Using List Comprehension

In all the approaches we have taken a list of lists named List with the following elements

 

Example:

List=[[1,3,5],[7,9,11],[13,15,17]]

Output:

And an empty list where we store the flattened list named flat_list.

 

Using append():

This is the simplest approach which is also termed shallow flattening. We use a nested for loop and iterate the lists in it using the iterator ‘i’ and in the inner for loop, we use the iterator ‘item’ to iterate through the inner lists.

Example:

List=[[1,3,5],[7,9,11],[13,15,17]]
flat_list = []
for i in List:
   for item in i:
      flat_list.appennd(item)
print('Flattened List is : ', flat_list)

Output:

 

Using Nested Loops:

It is much similar to the previous approach but here we add an if-else statement inside the nested for loop to check the type of items in the original list, as sometimes it can have string type also.

Example:

List=[[1,3,5],[7,9,11],[13,15,17]]
flat_list = []

for i in List:
   if type (element) is list:
      for item in elelment:
            flat_list.append(item)

else:
   flat_list.append(element)

print('Original List', List)
print('Flattened List is', flat_list)

Output:

Using List Comprehension:

This is a one-liner code where we have the same iterators ‘i’ to iterate through the list List and ‘item’ to iterate through the inner lists.

Example:

List=[[1,3,5],[7,9,11],[13,15,17]]
flat_list = [i for item in List for i in item]
print('Flattened List is', flat_list)

Output:

Leave a comment