Flattening a nested list involves converting a list of lists into a single list containing all the elements from the nested lists. This can be useful in various data processing tasks where a simplified, single-level list is required. There are different ways to achieve this in Python, including using recursion or list comprehensions. Here, we’ll demonstrate a recursive approach to flatten a nested list.
def flatten(nested_list):
# Initialize an empty list to store the flattened elements
flattened_list = []
# Recursive function to process each element in the nested list
def flatten_element(element):
# If the element is a list, recursively flatten it
if isinstance(element, list):
for item in element:
flatten_element(item)
else:
# If the element is not a list, append it to the flattened list
flattened_list.append(element)
# Start flattening from the top level of the nested list
flatten_element(nested_list)
return flattened_list
# Example usage
nested_list = [1, [2, 3], [4, [5, 6]], 7]
flattened_list = flatten(nested_list)
print(f"Flattened list: {flattened_list}")
flatten
FunctionThe flatten
function is defined to take a nested list as an argument. It initializes an empty list flattened_list
to store the flattened elements.
def flatten(nested_list):
flattened_list = []
A nested helper function flatten_element
is defined within flatten
to process each element in the nested list. This function uses recursion to handle elements that are lists themselves.
def flatten_element(element):
if isinstance(element, list):
for item in element:
flatten_element(item)
else:
flattened_list.append(element)
isinstance(element, list)
. If it is, the function iterates over each item in the list and recursively calls flatten_element
on it.flattened_list
.The flatten_element
function is initially called with the top-level nested_list
. This starts the recursion process to flatten all nested lists.
flatten_element(nested_list)
return flattened_list
An example nested list is defined and passed to the flatten
function. The resulting flattened list is printed.
nested_list = [1, [2, 3], [4, [5, 6]], 7]
flattened_list = flatten(nested_list)
print(f"Flattened list: {flattened_list}")