Flatten a Nested List in Python
To flatten a nested list in Python, you can use recursion, list comprehensions, or built-in functions like itertools.chain()
. Flattening a list means converting a nested list structure into a single-level list by extracting all elements recursively.
Examples
1. Flatten a Nested List Using Recursion
Recursion allows us to process each element and extract its contents if it is a list.
# Function to flatten a nested list using recursion
def flatten_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_list(item))
else:
flat_list.append(item)
return flat_list
# Example nested list
nested = [[1, 2, [3, 4]], [5, 6], 7]
# Flattening the list
flattened = flatten_list(nested)
# Printing the result
print("Flattened List:", flattened)
Explanation:
In this program, the flatten_list()
function iterates over the nested_list
. If an element is itself a list, we recursively call flatten_list()
to process it. Otherwise, we append the element to flat_list
. The function returns a fully flattened list.
Output:
Flattened List: [1, 2, 3, 4, 5, 6, 7]
2. Flatten a Nested List Using List Comprehension
List comprehension combined with recursion simplifies the flattening process.
# Function to flatten a nested list using list comprehension
def flatten_list(nested_list):
return [item for sublist in nested_list for item in (flatten_list(sublist) if isinstance(sublist, list) else [sublist])]
# Example nested list
nested = [[1, 2, [3, 4]], [5, 6], 7]
# Flattening the list
flattened = flatten_list(nested)
# Printing the result
print("Flattened List:", flattened)
Explanation:
Here, we use a nested list comprehension to iterate over each sublist
in nested_list
. If an element is a list, we recursively flatten it. Otherwise, we wrap it in a list and extract its elements.
Output:
Flattened List: [1, 2, 3, 4, 5, 6, 7]
3. Flatten a Nested List Using itertools.chain()
The itertools.chain()
function efficiently flattens lists but works only for one-level nested lists.
import itertools
# Example nested list
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Flattening the list using itertools.chain
flattened = list(itertools.chain(*nested))
# Printing the result
print("Flattened List:", flattened)
Explanation:
The itertools.chain()
function takes multiple iterables and treats them as a single sequence. We unpack the nested list using *nested
to pass each sublist as an argument to chain()
, flattening the structure.
Output:
Flattened List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
4. Flatten a Nested List Using a Stack (Iterative Approach)
An iterative approach using a stack avoids recursion limits.
# Function to flatten a nested list using an iterative stack approach
def flatten_list(nested_list):
stack = nested_list[::-1] # Reverse the list for stack processing
flat_list = []
while stack:
item = stack.pop()
if isinstance(item, list):
stack.extend(item[::-1]) # Add sublists in reversed order
else:
flat_list.append(item)
return flat_list
# Example nested list
nested = [[1, 2, [3, 4]], [5, 6], 7]
# Flattening the list
flattened = flatten_list(nested)
# Printing the result
print("Flattened List:", flattened)
Explanation:
The function uses a stack
to process elements iteratively, avoiding recursion. We iterate through the nested_list
in reverse and use pop()
to process elements. If an item is a list, we extend the stack; otherwise, we append it to flat_list
.
Output:
Flattened List: [1, 2, 3, 4, 5, 6, 7]
Conclusion
There are multiple ways to flatten a nested list in Python:
- Recursion: A clean, readable approach for deep nesting.
- List Comprehension: Compact and efficient for small lists.
itertools.chain()
: Works well for single-level nesting.- Stack-Based Iterative Approach: Handles deep nesting without recursion depth issues.