Flatten List Python

Flatten list Python

Flatten list in python means converting a multidimensional list into a single dimension list. the user can also perform the same for nested lists as well. For example, if the user wishes to convert [2,3,4], [12,32] into flatten list, the output will be [2,3,4,12,32]. This process of converting a multi-dimension list into a flatten list is called flattening. This method is performed by either using loops inside loops to flatten.

To Understand about Python Data Types

Flattening can be done in a number of ways such as by nested loops, by using some library functions in the code, by += operator, reduce method, NumpyFlat etc. The best way user can consider for flattening is nested loops though.

Flatten Program nested loops in python

List = [[10,25,36],[41,50,68],[70,87,94]]
List_flat = []

for i in range(len(List)):
  for j in range (len(List[i])): 
    List_flat.append(List[i][j]) 
    
print("Original List:",List)
print("Flattened List:",List_flat)

The output of the above python program will be:

('Original List:', [[10, 25, 36], [41, 50, 68], [70, 87, 94]])
('Flattened List:', [10, 25, 36, 41, 50, 68, 70, 87, 94])

The task in the above program is that the whole loss of the nested list is now a single form of flattening list. There can be unlimited lists to flatten. This can also be done using another method with is by importing itertools.

Flatten list python itertools

import itertools
lists = [[10,25,36],[41,50,68],[70,87,94]]
joinedlist = list(itertools.chain(*lists))
print(joinedlist)

The output of the above python program will be:

[10, 25, 36, 41, 50, 68, 70, 87, 94]

Check out the program below for flattening the lists using += operator in python:

lists = [[10,25,36],[41,50,68],[70,87,94]]
joinedlist = []
for list in lists:
joinedlist += list
print(joinedlist)  

The output of the above code using += operator will be:

[10, 25, 36, 41, 50, 68, 70, 87, 94]

There are some pre-defined rules for flattening the list which are:

  • The nested lists have to be present inside the square brackets only.
  • The flattened list will be return inside the square brackets only.
  • Flatten list will only remove the inner brackets of the  enclosed elements.
  • It is not possible to perform any calculations inside the square brackets or inner lists.

Leave a comment

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