Write a Python Program to Flatten a Nested List

Flattening a nested list is the process of converting a list that contains nested lists into a single list that contains all the elements from the original lists, without any nesting.

In Python, this can be achieved using recursion or iteration.

In this tutorial, we will discuss both approaches.


Using Recursion

The first approach to flatten a nested list is to use recursion.

This approach involves defining a recursive function that takes in a nested list as an argument and returns a flattened list.

Here is the Python code to implement this approach:

def flatten_list(nested_list):
    flattened_list = []
    for item in nested_list:
        if isinstance(item, list):
            flattened_list.extend(flatten_list(item))
        else:
            flattened_list.append(item)
    return flattened_list

In this code, we define a function called flatten_list that takes in a nested list as an argument.

Inside the function, we create an empty list called flattened_list that we will use to store the flattened list.

Next, we loop through each item in the nested list.

If the item is a list, we call the flatten_list function recursively to flatten the item and add its elements to the flattened_list.

If the item is not a list, we simply append it to the flattened_list.

Finally, we return the flattened_list.

Using Iteration

The second approach to flatten a nested list is to use iteration.

This approach involves using a stack to keep track of the elements in the nested list and flattening the list by popping elements from the stack.

Here is the Python code to implement this approach:

def flatten_list(nested_list):
    flattened_list = []
    stack = [nested_list]
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(item)
        else:
            flattened_list.append(item)
    return flattened_list

In this code, we define a function called flatten_list that takes in a nested list as an argument.

Inside the function, we create an empty list called flattened_list that we will use to store the flattened list.

Next, we create a stack that initially contains the nested list.

We then enter a while loop that continues as long as the stack is not empty.

Inside the loop, we pop an element from the stack and check if it is a list.

If it is a list, we add its elements to the stack. If it is not a list, we append it to the flattened_list.

Finally, we return the flattened_list.


Conclusion

Flattening a nested list is a common task in Python programming.

In this tutorial, we discussed two approaches to flatten a nested list: using recursion and using iteration.

Both approaches are valid and can be used depending on the specific requirements of the task at hand.