![]() |
Flattening a list of lists is a common task in Python, often encountered when dealing with nested data structures. Here, we’ll explore some widely-used methods to flatten a list of lists, employing both simple and effective techniques. How To Flatten A List Of Lists In Python?Below, are the methods for How To Flatten A List Of Lists In Python.
Using Nested LoopsIn this example, below code initializes a nested list and flattens it using nested loops, iterating through each sublist and item to create a flattened list. The result is then printed using Python3
Output
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9] Using List ComprehensionIn this example, below code starts with a nested list and uses list comprehension to flatten it into a single list. The result, a flattened list, is displayed using `print(“Flattened List:”, flattened_list)`. Python3
Output
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9] Using
|
from itertools import chain # Sample List of Lists nested_list = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] # Flatten using itertools.chain() flattened_list = list (chain( * nested_list)) # Display the result print ( "Flattened List:" , flattened_list) |
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
functools.reduce()
Using functools.reduce()
with the operator concat
function is another option. reduce()
applies concat
successively to the elements of the list, achieving flattening.
from functools import reduce from operator import concat # Sample List of Lists nested_list = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] # Flatten using functools.reduce() and operator.concat flattened_list = reduce (concat, nested_list) # Display the result print ( "Flattened List:" , list (flattened_list)) |
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |