Python

Python Flatten List of Lists

The list is the most commonly used structure in Python. A two-dimensional list is also recognized as a list of lists. Transforming a 2D array into a one-dimensional array is known as flattening. Flattening a list of lists needs altering a two-dimensional list into a one-dimensional list by unnesting every list item saved in the list of lists. You can perform the flattening process using nested for loops, list comprehensions, and the NumPy method by importing Python libraries. Flattening a list means eliminating a dimension from a Python list. A list holds many dimensions. It means that you have a list and sublists. Come and let’s explain it with the help of examples.

Example 1:

Our first illustration is a basic approach to finding a flat list by choosing every element from the list of lists and adding it to a one-dimensional list. The code is in-built and works for both equal and unequal lists of lists. We implement “flatten a list of lists” by using the Spyder compiler in Windows 10.

We create a new file. Then, define a function that takes a 2D list as an argument and initializes a blank list called f_1. Next, we use a nested loop function and if-else statements. The nested loop traverses over the external list. If function checks the condition if it meets the given condition and the element matches the list type. Then, it traverses through the sub-list and calls the append function, which takes “i” as a parameter; otherwise, it moves to the else statement. Then, we create and initialize the list of integers. Then, use the print function to print original list values. We can then print the flattened list of lists:

def f_l(_2d_list):
f_l = []
for e in _2d_list:
if type(e) is list:
for i in e:
f_l.append(i)
else:
f_l.append(e)
return f_l
n_l = [[11, 12, 13, 14], [15, 16, 17], [18, 19, 20]]
print('The Original List is here', n_l)
print('The Transformed Flat List is here', f_l(n_l))

Save and execute the code program, and the transformed flatten list is shown on the console screen.

Example 2:

Our second illustration provides a well-designed but less instinctive solution to create a flat list based on the two-dimensional list. We use the list comprehension method to flatten lists of lists by using the Spyder compiler in Windows 10. We use the same source code file and create two lists. We initialize a list known as r_1.

Then, we use a syntax that takes an item from the sublists. We can use two print functions. The first one displays the original list, and the second one shows the resultant flattened list of lists:

r_l = [[13, 23, 33, 43], [53, 63, 73], [83, 93]]
f_l = [item for sublist in r_l for item in sublist]
print('Check the original list', r_l)
print('Now check the output', f_l)

Again, save (Ctrl+S) and execute the program code, and then, view the flatten list on the console screen:

Example 3:

In our third illustration, we use the NumPy method, which is simple and efficient. Numpy is a numerical Python module that performs mathematical operations on an array. Python Concatenate function uses a “+” operator that helps you merge two or more Python strings. The “+” operator appears between the two strings you wish to combine. Let’s check how it works. We use the same code file and import a NumPy module.

We can create and initialize a list of sublists with integer values, strings, characters, and Boolean. After this, we call numpy.concatenate() function and assign it to a variable. The function merges all elements in the list. At last, we use a print statement that displays the concatenate output on the console screen:

import numpy
l = [[19, 29, 39], [True, False], [0.1, 0.3, 0.0], ['x', 'y', '']]
jl = list(numpy.concatenate(l).flat)    
print(jl)

Again, press Ctrl+S to save the file and then, hit F5 to execute the program and check the output on the console screen:

Conclusion:

In this tutorial, we have added a comprehensive list of methods to finish flattening a list of lists. The NumPy and comprehension method is very simple and easy. You don’t need to use too many lines of code. But the nested loop method is a bit tricky as compared to other ones. We hope you found this article useful. Thank you for reading and check out other informative articles at Linux Hint.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content