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

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

How to make a flat list out of a list of lists? – 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

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.

 

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.

 

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.

Leave a comment