Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to flatten a nested list - Python Program

Example 1 :

def flatten_list(nested): """Flatten a nested list recursively.""" flat = [] for item in nested: if isinstance(item, list): flat.extend(flatten_list(item)) else: flat.append(item) return flat print(flatten_list([1, [2, [3, 4]], 5]))

Output

 
OUTPUT  :
[1, 2, 3, 4, 5]

Example 2 : Advanced Program

def flatten_list_recursive(nested_list): """ Recursively flattens a nested list into a single-dimensional list. Args: nested_list: The list to be flattened, which may contain nested lists. Returns: A new list containing all elements from the original nested list in a flattened, single-dimensional structure. """ flattened = [] for item in nested_list: if isinstance(item, list): # If the item is a list, recursively call the function # and extend the current flattened list with the result. flattened.extend(flatten_list_recursive(item)) else: # If the item is not a list, append it directly. flattened.append(item) return flattened # Example Usage: my_nested_list = [1, [2, 3], [4, [5, 6]], 7, [8]] flattened_result = flatten_list_recursive(my_nested_list) print(f"Original nested list: {my_nested_list}") print(f"Flattened list: {flattened_result}")

Output

 
OUTPUT  :
Original nested list: [1, [2, 3], [4, [5, 6]], 7, [8]]
Flattened list: [1, 2, 3, 4, 5, 6, 7, 8]