Python Program - Flatten a Nested List
here's a Python program that flattens a nested list:
def flatten_list(nested_list): """ Flattens a nested list. Args: nested_list: A nested list. Returns: A flattened list. """ flattened_list = [] for item in nested_list: if isinstance(item, list): # recursively call flatten_list if item is a list flattened_list.extend(flatten_list(item)) else: flattened_list.append(item) return flattened_list # Example usage: nested_list = [[1, 2, [3]], 4] flattened_list = flatten_list(nested_list) print(flattened_list) # Output: [1, 2, 3, 4]
In this program, we define a function called flatten_list()
that takes a nested list as its argument, and returns a flattened list.
Inside the function, we first create an empty list called flattened_list
.
We then loop through each item in the input nested_list
. If the item is a list, we recursively call flatten_list()
on that item, and extend flattened_list
with the flattened list returned by that call. If the item is not a list, we simply append it to flattened_list
.
Finally, we return the flattened list.
In the example usage, we create a nested list [[1, 2, [3]], 4]
, and call flatten_list()
on it to get the flattened list [1, 2, 3, 4]
. We then print out the flattened list using the print()
function.