Flatten a list in python

Table of Contents What is a “Flattening a list in python”?How can we achieve flattening a list in python?Comprehension list:Nested for loops:Itertools:Functools:NumPyLambda:Sum() function:Conclusion: What is a “Flattening a list in python”? A list is the …

flatten-a-list-in-python

What is a “Flattening a list in python”?

A list is the most convenient way to organize data in python.

Flattening a list in python refers to the dimensions or the coordinates that are used to locate the items in it.

We use “flattening a list on python” in python lists of lists convert it into a single list.

Sometimes a list of lists is referred to as a nesting list and flattening a list is an operation that is performed to convert it into a simple list.

Let’s understand it as dimensions or coordinates, list of lists is a 2-D (2 dimensional) list means every item of a list is also a list itself.

List of lists in 2D: [ [a,b,c], [d,e,f], [x,y,z] ]Flattening a list into 1D : [a, b, c, d, e, f, x, y, z].

How can we achieve flattening a list in python?

There are several approaches, you can follow to achieve flattening a list in python.

  • Comprehension 
  • Nested for loops
  • itertools 
  • Funct-tools
  • NumPy 
  • Lambda
  • Sum()

Comprehension list:

Comprehension list in python is a method to flatten a list means creating a new list from an existing list iterables.

Let’s see how it works with an example:

Example:

if __name__ == '__main__':
    lists = [[1, 2, 3], [4,5], [6, 7, 8], ['ab', 'bc', 'ca']]
    joinlist = [x for list in lists for x in list]
    print(joinlist)

In the above example of the comprehension list, we first declare the “if” statement and then the 2D list that has to be converted into a 1D list or regular simple list, after that we used the joinlist method to flatten it.

In the end, we used the print function to print the flattened list.

Output :

[1, 2, 3, 4, 5, 6, 7, 8, 'ab', 'bc', 'ca']

Nested for loops:

As the name indicates itself “nested loops”, nested loops mean loops inside the loops. The inner loop will be executed for each iteration of the outer loop.

Nested for loops in python is also a method that can be used to flatten the list.

Or we can say this is a method from which we can append all the items of a nested list into a simple list.

Let’s understand this with the help of an example:

Example:

lists = [[1, 2, 3], [4,5], [6, 7, 8], ['ab', 'bc', 'ca']]
joinedlist = []
for x in range(len(lists)): 
  for y in range (len(lists[x])): 
    joinedlist.append(lists[x][y])     
print(joinedlist)

In this example, we flatten a list by using the nested loop method.

First, we started the list that has to be flattened, then used the joinlist method.

Transversing through each list and then used the append method to flatten a list and in the end, we used the print function to print the flattened list.

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 'ab', 'bc', 'ca']

Itertools:

Itertools is a module in the python standard library. It allows us to perform various functions that work on the iterators.

Itertools.chain is the function of itertools that can be used to flatten a list into a simple regular list.

Let’s understand it better with the help of an example:

Example:

import itertools

if __name__ == '__main__':
    lists = [[1, 2, 3], [4, 5], [6, 7, 8], ['ab', 'bc', 'ca']]
    joinedlist = list(itertools.chain(*lists))
    print(joinedlist)

In the above example, we first imported the itertools with the “import”  function

And then used if statement and after that the list that has to be flattened and then we used joindlist method to add itertools.chain method into the code and at the end used print function to print the sorted single simple list.

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 'ab', 'bc', 'ca']

Functools:

Functools is a module in python for higher-order functions that work on other functions or operations.

In common any callable object can be treated as a function on this module.

It can also be used to flatten a list in python.

Let’s understand this better with an example:

Example:

import operator
from functools import reduce

if __name__ == '__main__':
    lists = [[1, 2, 3], [4,5], [6, 7, 8], ['ab', 'bc', 'ca']]
    joinedlist = reduce(operator.add, lists)
    print(joinedlist)

In this example, 

First, we imported the operator from functool and imported reduce function

Then used the if statement

After that, the list has to be flattened.

Then, the joinedlist method 

In the end, used the print function to print the sorted list.

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 'ab', 'bc', 'ca']          

NumPy

Numpy is a Python standard library for numerical python functions. NumPy consists of a multi-dimensional array of objects.

Concatenation is a function of a  numpy that can be used to flatten the list.

Let’s check its example:

Example:

import numpy

lists = [[1, 2, 3], [4,5], [6, 7, 8], ['ab', 'bc', 'ca']]

joinedlist = list(numpy.concatenate(lists).flat)    
print(joinedlist)

In this above  example:

We first imported the NumPy library 

Then, the list to be flattened

Next, joinedlist function in which we used NumPy’s concatenation function to flatten the list.

In the end, used the print function to print the flattened list.

Output:

['1', '2', '3', '4', '5', '6', '7', '8', 'ab', 'bc', 'ca']

Lambda:

Lambda is a small anonymous function used as a keyword in python.

It will allow you to create a small function usually not more than a line.

It is also used to convert the 2D list into 1D.

 Let’s see an example:

Example:

lists = [[1, 2, 3], [4, 5], [6, 7, 8], ['ab', 'bc', 'ac']]
joinedlist = lambda lists:[element for item in lists for element in joinedlist(item)] if type(lists) is list else [lists]

print(joinedlist(lists))

In this example, 

at first, we added the list to be flattened

then, used lambda function within the joinedlist method

and in the end, used print function to print the flattened simple list.

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 'ab', 'bc', 'ac']

Sum() function:

The Sum of numbers in the list is the requirement almost everywhere.

Python provides the build-in function Sum(), which is used, to sum up the list items.

And it is also used to change the list of lists into a single simple list.

In short, or simply it can also be used to flatten a list.

Let’s see this with the help of an example:

Example:

if __name__ == '__main__':
    lists = [[1, 2, 3], [4, 5], [6, 7, 8], ['ab', 'bc', 'ca']]
    joinedlist = sum(lists, [])
    print(joinedlist)

In this example,

First, we used the “if” statement

Then, the list that has to be flattened 

And after that, the joinedlist method used the Sum() function.

In the end, used the print function to print the flattened list.

Output:

[ 1, 2, 3, 4, 5, 6, 7, 8, 'ab', 'bc', 'ca' ]

Conclusion:

In this article, we are targeting “Flatten a list in python” which converts a list of lists into a single list. we cover seven methods to flatten a list in python from 2-D to 1-D with easy programming examples.

Leave a Comment