In Python, the most flexible data structure is a list. Multiple dimensions can be present in a Python list. This means you’ve got a list within a list. These lists are also known as nested lists. If we have a nested list as a Python data container, we may need to convert it to a flattened list so that each piece can be handled further.
Flattening a List
The process of removing a dimension from a list is referred to as Flattening a List. A dimension is an extra coordinate required to locate an item in a list. Flattening a list of lists (nested lists) means transforming a 2D list into a 1D list by un-nesting each list item in the list of lists – that is, for example – changing a nested list [[1, 2, 3], [4, 5, 6], [7, 8, 9]] into a single list [1, 2, 3, 4, 5, 6, 7, 8, 9].
Depending on the regularity and depth of the nested lists, flattening can be accomplished via nested for loops, list comprehensions, recursion, built-in functions, or by importing libraries in Python.
Example 1: Using List Comprehension
A Python list comprehension creates a new list from the contents of an old one. By adding criteria or changes within the comprehension, you can alter each piece that gets into your new list. Comprehensions provide syntactic sugar for iterating over a list and generating a new list using a for loop.
my_list = [['Sam', 'Tim', 'John'], ['Car', 'Bike'], ['Employees']]
print('Original List:', my_list)
flat_list = [num for sublist in my_list for num in sublist]
print('Flattened List:', flat_list)
Output
Original List: [['Sam', 'Tim', 'John'], ['Car', 'Bike'], ['Employees']]
Flattened List: ['Sam', 'Tim', 'John', 'Car', 'Bike', 'Employees']
Example 2: Using Nested for Loops (Non pythonic way)
Using a layered Python for loop, we can achieve the same result. The term “nested for loop” refers to “a for loop within a for loop.” In most circumstances, a list comprehension is preferable to a for loop. List comprehensions are shorter and easier to comprehend than nested for loops in this scenario.
food = [['Apple', 'Banana', 'Kiwi'], ['Carrot', 'Tomato'], ['Cucumber']]
print('Original List:', food)
flat_list = []
for sublist in food:
   for i in sublist:
       flat_list.append(i)
print('Flattened List:', flat_list)
Output
Original List: [['Apple', 'Banana', 'Kiwi'], ['Carrot', 'Tomato'], ['Cucumber']]
Flattened List: ['Apple', 'Banana', 'Kiwi', 'Carrot', 'Tomato', 'Cucumber']
Example 3: Using itertools package
Itertools is a Python standard library module. The module has a number of methods that make it simple to interact with iterable objects and generators. We can generate a flattened list with the itertools module.
- The itertools module’s chain() method returns each element of each iterable (i.e. sub lists)
- list() creates a list from the returned values.
import itertools
my_list = [[1, 2, 3], ['One', 'Two', 'Three'], [0.0, 0.1]]
print('Original List:', my_list)
flat_list = list(itertools.chain(*my_list))
print('Flattened List:', flat_list)
Output
Original List: [[1, 2, 3], ['One', 'Two', 'Three'], [0.0, 0.1]]
Flattened List: [1, 2, 3, 'One', 'Two', 'Three', 0.0, 0.1]
Example 4: Using sum()
Another option is to sum over inner lists. The function takes two parameters: iterable, which is a list of lists, and start, which in our instance is an empty list that serves as the initial flat list to which items from the inner sublists are appended. This method is easy because there is no need to import anything, but it is slower than itertools() and chain() when the number of sublists is big.
my_list = [[1, 2, 3], ['One', 'Two', 'Three'], [0.0, 0.1]]
print('Original List:', my_list)
flat_list = sum(my_list, [])
print('Flattened List:', flat_list)
Output
Original List: [[1, 2, 3], ['One', 'Two', 'Three'], [0.0, 0.1]]
Flattened List: [1, 2, 3, 'One', 'Two', 'Three', 0.0, 0.1]
Example 5: Using lambda and reduce()
from functools import reduce
my_list = [[1, 2, 3], ['One', 'Two', 'Three'], [0.0, 0.1]]
print('Original List:', my_list)
flat_list = reduce(lambda x, y: x+y, my_list)
print('Flattened List:', flat_list)
Output
Original List: [[1, 2, 3], ['One', 'Two', 'Three'], [0.0, 0.1]]
Flattened List: [1, 2, 3, 'One', 'Two', 'Three', 0.0, 0.1]
Leave a Reply