Flatten list Python

Hello programmers, in todays article, we will be discussing different ways to flatten a list in python. We will be learning about 25 distinct ways to flatten multidimensional or nested lists into single-dimensional ones. Out of all ways that we will be going through, you can choose the process you like the best easy and needful for your program.

Before we start with different ways to flatten lists in python, let me just brief you about what a list is and what do we mean by flattening a list.

List List in Python is collecting any number of different items in the order and mutable. The list is created by placing all its elements inside square brackets[], separated by a comma. The items may be of different data types, i.e., a list might have an integer, float, and string items together. A list that has another list as its items is called a nested list.

A simple list in Python :-

X = [1, 3, 5]

A nested list:

Y = [[1,2,3], [4, 5, 6], [7, 8, 9]]

Flattening a list in python Flattening lists in python means converting multidimensional lists into one-dimensional lists. It is basically a method of merging all the sublists of a nested list into one unified list. For example, the flattened list of the nested list Y = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] is given as Y = [1, 2, 3, 4, 5, 6, 7, 8, 9]

In this tutorial we will be discussing in details the 25 Different ways to flatten list in python:

  1. Shallow Flattening
  2. List Comprehension
  3. Deep Flattening
  4. Recursion Method
  5. Without Recursion
  6. With Itertools
  7. Using Reduce Function
  8. NumPy Ravel
  9. Using NumPy Flatten
  10. NumPy Reshape
  11. Using NumPy flat
  12. NumPy concatenate
  13. Lambda Function
  14. One-Line Command
  15. 15. Sum function
  16. Functools Reduce + Operator.concat
  17. Functools Reduce + Operator.iconcat
  18. Using Django Flatten
  19. By using Pandas Flatten
  20. Using Matplotlib Flatten
  21. Using Unipath Flatten
  22. ByuUsing Setuptools Flatten
  23. Using NLTK Flatten
  24. Using Generator
  25. Flatten a Dictionary to List

Contents

  • 1. Flatten List in Python Using Shallow Flattening:
  • 2. Flatten List in Python Using List Comprehension:
  • 3. Flatten List in Python Using Deep Flattening:
  • 4. Flatten List in Python Using Recursion Method:
  • 5. Flatten List in Python Using Without Recursion:
  • 6. Flatten List in Python With Itertools:
  • 7. Flatten List in Python Using Reduce Function:
  • 8. Flatten List in Python Using NumPy Ravel:
  • 9. Flatten List in Python Using NumPy Flatten:
  • 10. Flatten List in Python Using NumPy Reshape:
  • 11. Flatten List in Python Using NumPy flat:
  • 12. Flatten List in Python Using NumPy concatenate:
  • 13. Flatten List in Python using Lambda Function:
  • 14. Flatten List in Python using One Line Command
  • 15. Sum function
  • 16. Functools Reduce + Operator.concat
  • 17. Functools Reduce + Operator.iconcat
  • 18. Using Django Flatten
  • 19. Using Pandas Flatten
  • 20. Using Matplotlib Flatten
  • 21. Using Unipath Flatten
  • 22. Using Setuptools Flatten
  • 23. Using NLTK Flatten
  • 24. Using Generator
  • 25. Flatten a Dictionary to List
  • Must Read
  • Conclusion

1. Flatten List in Python Using Shallow Flattening:

Example:

l = [[0,1],[2,3]] flatten_list = [] for subl in l: for item in subl: flatten_list.append[item] print[flatten_list]

Output:

[0, 1, 2, 3]

Explanation:

This simple example flattens a list of lists by converting [[0, 1], [2, 3]] into [0, 1, 2, 3]. The method in the above example of flattening a list is called shallow flattening. It is only used with a list of lists having the same depth.

2. Flatten List in Python Using List Comprehension:

Example:

A = [[0,1], [2,3]] flatten_list = [item for subl in l for item in subl] print[flatten_list]

Output:

[0, 1, 2, 3]

Explanation:

Using list comprehension is a method of flattening lists in a single line of code. If we break the code, it basically comprises of a nested for loop. The first loop is for a sub in l and the second loop is for an item in sub.

3. Flatten List in Python Using Deep Flattening:

Example:

from iteration_utilities import deepflatten multi_depth_list = [[0,1], [[5]], [6,4]] flatten_list = list[deepflatten[multi_depth_list]] print[flatten_list]

Output:

[0, 1, 5, 6, 4]

Explanation:

The deep Flattening method provides flattening of a list of lists having varying depths. If shallow flattening were used for the above example, it would give the output [0, 1, [5], 6, 4]. This is not our desired output, so the deep flattening method is used, which overcomes the shallow flattening methods drawback. There is a built-in function called deepflatten[] in the iteration_utilities library, enabling you to implement this method to flatten the list. However, to implement this deepflatten[] function in your program, you need to install the iteration_utilities package from pip as it not available in python by default.

4. Flatten List in Python Using Recursion Method:

Example:

def flatten[l1] if len[l1] == 1: if type[l1[0]] == list: result = flatten[l1[0]] else: result = l1 #recursive case elif type[l1[0]] == list: result = flatten[l1[0]] + flatten[l1[1:]] else: result = [l1[0]] + flatten[l1[1:]] return result list1 = [[0,1], [[5]], [6, 7]] flatten[list1]

Output:

[0, 1, 5, 6, 7]

Explanation:

Here we are using the recursion method to flatten the list. In this example, we call the function recursively inside itself to run till the end. The base case in the above example checks if the length is 1. If its true, it then checks whether the type of the first index of the list is a list. Only if its true, it calls the function to flatten the list or else stores it as an ordinary number.

5. Flatten List in Python Using Without Recursion:

Example:

def flatten_without_rec[non_flat]: flat = [] while non_flat: #runs until the given list is empty. e = non_flat.pop[] if type[e] == list: #checks the type of the poped item. non_flat.extend[e] #if list extend the item to given list. else: flat.append[e] #if not list then add it to the flat list. flat.sort[] return flat l= [[0, 1], [[5]], [6, 7]] flatten_without_rec[l]

Output:

[0, 1, 5, 6, 7]

Explanation:

To Flatten without Recursion, we define a function called flatten_without_rec[]. This function runs the while loop until all the elements are popped out of the nested list of variable depth. The control enters the while loop till the given list becomes emp. Once it gets into the loop, it checks the type of item popped out of the list. If the item is a list, then the loop is again to be run over it. If not, then it is added to the flat list.

6. Flatten List in Python With Itertools:

Example:

import itertools List_1 = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattened List_flat = list[itertools.chain[*List_1]] print[List_flat]

Output:

[1,2,3,4,5,6,7,8,9]

Explanation:

Importing itertools to your python program gives you access to its in-built function called itertools.chain[], which merges various lists of the nested list into a unified list. The 2-D list to be flattened is passed as an argument to the itertools.chain[] function.

7. Flatten List in Python Using Reduce Function:

Example:

from functools import reduce multi_depth_list = [[3,2,1],[1,4,5]] reduce[list.__add__, [list[items] for items in multi_depth_list

Output:

[3,2,1,1,4,5]

Explanation:

This is a very simple way of flattening lists by using a function named reduce[]. This function is a built-in function of the functools library. You will just have to import the reduction from the functools.

8. Flatten List in Python Using NumPy Ravel:

The NumPy library has three built in functions that can convert nested list and multi dimensional arrays into flattend lists. The three functions are : numpy.ravel[], numpy.flatten[], numpy.reshape[-1].

numpy.ravel[]

import numpy as np list1 = np.array[[[3,2,1], [4,5,6], [7,8,9]]] out = list1.ravel[] print[out]

Output:

[3,2,1,1,4,5]

9. Flatten List in Python Using NumPy Flatten:

Example:

import numpy as np lst = np.array[[[3,2,1], [4,5,6], [7,8,9]]] out = lst.flatten[] print[out]

Output:

[3,2,1,1,4,5]

Explanation:

Numpy array has a flatten[] method which allows it to reduce the dimensions of the array to 1. With optimized algorithms and better functionality, this method is one of the fastest methods to flatten a list. Note that the flatten[] method doesnt change the contents of an existing array. Instead, it returns a new flat array.

10. Flatten List in Python Using NumPy Reshape:

Example:

import numpy as np lst = np.array[[[3,2,1], [4,5,6], [7,8,9]]] out = lst.reshape[-1] print[out]

Here the output will be same because all the three function is used to flatten list in python.

Output:

[3,2,1,4,5,6,7,8,9]

Explanation:

The NumPy package is not present in the python by default. To use these builtin flattening functions of this package, you will have to install it from pip. All three functions perform the flattening of lists and return the same output. The difference lies only in their time complexities, i.e., their speed. The flatten function returns a copy every time it flattens the array. Consequently, it takes a longer time when dealt with a larger set of values.

11. Flatten List in Python Using NumPy flat:

Example:

import numpy as np lst = np.array[[[3,2,1], [4,5,6], [7,8,9]]] print[list[lst.flat]]

Output:

[3,2,1,4,5,6,7,8,9]

Explanation:

The numpy array has a flat attribute that returns the flattened object of an n-dimensional array. This attribute is used to iterate through all the elements in the 1D reshaped array.

12. Flatten List in Python Using NumPy concatenate:

Example:

import numpy as np lst = np.array[[[3,2,1], [4,5,6], [7,8,9]]] print[list[numpy.concatenate[lst]]]

Output:

[3,2,1,1,4,5]

Explanation:

Numpy concatenate is a python function that adds all the sub-arrays of the array. With this method, you can only flatten a 2d list in python. Concatenation is a substitute of a extend[] or + operator.

13. Flatten List in Python using Lambda Function:

Lambda function are the easiest way of declaring functions in single line. With the ability to take and return the parameter, you can perform various operations within it. Flattenning an array is also a possible by using list comprehension and lambda functions.

Example:

flatten = lambda x: [i for row in x for i in row] lst = [[3,2,1], [4,5,6], [7,8,9]] out = flatten[lst] print[out]

Output:

[3,2,1,4,5,6,7,8,9]

Explanation:

In-built lambda command in Python helps you build short functions in a single line. By combining this with list comprehension, you can fatten an array as given in the above examples. Firstly, we start by creating a lambda function called flatten. This function uses a nested list comprehension to create a new array with every element. Then we called flatten array by passing the 2d array. The function returns a flattened array, which can be seen in the output.

14. Flatten List in Python using One Line Command

Last but not least, there is a one-liner trick you can use to flatten an array in python. With the introduction of list comprehension techniques, you can initialize an array in a single line using for loops. As we have a 2-d array, well use 2 for loops inside a single line in a list comprehension. Lets head over to the code

Example:

print[[i for row in [[3,2,1], [4,5,6], [7,8,9]] for i in row]]

Output:

[3, 2, 1, 4, 5, 6, 7, 8, 9]

Explanation:

The code starts with initializing a list with a statement for in []. This statement is followed by the i in row statement, which allows us to capture every single element from a nested array.

15. Sum function

Example:

l = [[1, 2, 3], [4, 5], [6]] l = sum[l, []] print[l]

Output:

[1,2,3,4,5,6]

Explanation:

The default sum function has a second parameter as a chaining operator. Bypassing [] as the parameter, you ensure that the returning datatype is of the list. This method is used by many programmers to flatten a list in python.

16. Functools Reduce + Operator.concat

Example:

import functools import operator def functools_reduce[a]: return functools.reduce[operator.concat, a] l = [[1, 2, 3], [4, 5], [6]] print[functools_reduce[l]]

Output:

[1,2,3,4,5,6]

Explanation:

The functools reduce function accepts a concatenating operator and a list. It applies a concatenating operator between all the elements of the list and returns a flattened array.

17. Functools Reduce + Operator.iconcat

Example:

import functools import operator def functools_reduce[a]: return functools.reduce[operator.iconcat, a] l = [[1, 2, 3], [4, 5], [6]] print[functools_reduce[l]]

Output:

[1,2,3,4,5,6]

Explanation:

Iconcat function refers to the in-place algorithm. This operator function replaces the previous value of iteration with a new value. The functools reduce function accepts this operator and a list. It applies a concatenating operator between all the elements of the list and returns a flattened array.

18. Using Django Flatten

Example:

from django.contrib.admin.utils import flatten l = [[1,2,3], [4,5], [6]] print[flatten[l]]

Output:

[1,2,3,4,5,6]

Explanation:

Flatten function from django.contrib.admin.utils allow you to flatten an array easily. This method is pre-included in the Django library. If you dont have Django installed, run pip install django in your terminal.

19. Using Pandas Flatten

Example:

from pandas.core.common import flatten l = [[1,2,3], [4,5], [6]] print[list[flatten[l]]]

Output:

[1,2,3,4,5,6]

Explanation:

Flatten function from pandas.core.common allows you to flatten an array easily. This method is pre-included in the Pandas library. If you dont have Pandas installed, run pip install pandas in your terminal.

20. Using Matplotlib Flatten

Example:

from matplotlib.cbook import flatten l = [[1,2,3], [4,5], [6]] print[list[flatten[l]]]

Output:

[1,2,3,4,5,6]

Explanation:

Flatten function from matplotlib.cbook allows you to flatten an array easily. This method is pre-included in the Matplotlib library. If you dont have Matplotlib installed, run pip install matplotlib in your terminal.

21. Using Unipath Flatten

Example:

from unipath.path import flatten l = [[1,2,3], [4,5], [6]] print[list[flatten[l]]]

Output:

[1,2,3,4,5,6]

Explanation:

Flatten function from unipath.path allows you to flatten an array easily. This method is pre-included in the Unipath library. If you dont have Unipath installed, run pip install unipath in your terminal.

22. Using Setuptools Flatten

Example:

from setuptools.namespaces import flatten l = [[1,2,3], [4,5], [6]] print[list[flatten[l]]]

Output:

[1,2,3,4,5,6]

Explanation:

Flatten function from setuptools.namespaces allows you to flatten an array easily. This method is pre-included in the setuptools library. This library is available in your python installation by default.

23. Using NLTK Flatten

Example:

from nltk import flatten l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] print[flatten[l]]

Output:

[1,2,3,4,5,6, 7, 8, 9]

Explanation:

Flatten function from nltk allows you to flatten an array easily. This method is pre-included in the NLTK library. If you dont have NLTK installed, run pip install nltk in your terminal.

24. Using Generator

Example:

def flatten[items]: """Yield items from any nested iterable; see REF.""" for x in items: if isinstance[x, list] and not isinstance[x, [str, bytes]]: yield from flatten[x] else: yield x l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] print[list[flatten[l]]]

Output:

[1,2,3,4,5,6,7,8,9]

Explanation:

Generators are a special type of function which yields the values step by step from a function. The main advantage of these functions is that they can be called whenever you require a new value. In this way, memory consumption is reduced. We first start by defining a function called flatten[]. This function checks if the parameter is iterable then flattens it. This way you can generate an entire flattened array.

25. Flatten a Dictionary to List

Example:

d = {'python': 0, 'pool': 1} l = [] for k in d: l.append[k] l.append[d[k]] print[l] #Alternative l = [i for n in [[k, z] for k,z in d.items[]] for i in n] print[l]

Output:

['python', 0, 'pool', 1]

Explanation:

You can flatten a dictionary into an array by using a simple for loop. Moreover, you can also customize the list sequence according to your need.

Must Read

  • Introduction to Python Super With Examples
  • Python Help Function
  • Why is Python sys.exit better than other exit functions?
  • Python Bitstring: Classes and Other Examples | Module

Conclusion

There are multiple ways to flatten a list in python. The best way to flatten a list depends on your programs needs and the libraries you are using. Multidimensional arrays and nested lists having varying sizes and depths are also flattened. You can use any of the above methods to flatten the list in your python program, depending upon your choice and ease.

Still have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Video liên quan

Chủ Đề