Python - Remove all occurrences in nested list

When working with nested lists in Python, there are situations where we need to remove all occurrences of a specific element. Whether it's filtering unwanted data or simplifying complex structures, removing elements from nested lists is a common task. In this article, we'll explore different approaches to achieve this goal using recursion and list manipulation techniques.

Advantages of Removing All Occurrences in Nested Lists

Simplicity and Readability ? Python provides clean and intuitive syntax, making it easier to write and understand code. Removing all occurrences in a nested list using Python is straightforward, thanks to its simplicity and readability.

Flexibility ? Python offers multiple approaches to remove all occurrences in nested lists, giving developers the flexibility to choose the method that best fits their specific requirements. Whether using list comprehension, recursion, or iterative algorithms, Python allows for flexibility in implementing solutions.

Powerful List Manipulation ? Python provides robust built-in functions and methods for manipulating lists. By leveraging these features, removing all occurrences in nested lists becomes seamless. Functions like remove(), del, and list comprehension make it easy to filter out unwanted elements.

Handling Complex Nested Structures ? Nested lists often represent complex data structures. Python's ability to handle nested structures efficiently makes it ideal for removing all occurrences in such scenarios. The recursive approach streamlines the removal process by traversing through nested levels.

Approach 1: Using Recursion with New List Creation

Algorithm

  • Step 1 ? Create a function named remove_occurrences() and initialize an empty result list.

  • Step 2 ? Use a for loop to iterate through each element in the nested list.

  • Step 3 ? If the item is a list, recursively call the remove_occurrences() function on its sublists.

  • Step 4 ? If the element does not match the target element, add it to the result list.

  • Step 5 ? Return the result list.

Example

def remove_occurrences(nested_list, target):
    result = []
    for element in nested_list:
        if isinstance(element, list):
            result.append(remove_occurrences(element, target))
        elif element != target:
            result.append(element)
    return result

# Test the function
nested_list = [1, [2, 3, 2], [4, [5, 2, 6]], 2]
target = 2
output = remove_occurrences(nested_list, target)
print("Original list:", nested_list)
print("After removing", target, ":", output)
Original list: [1, [2, 3, 2], [4, [5, 2, 6]], 2]
After removing 2 : [1, [3], [4, [5, 6]]]

Approach 2: Using Recursion to Modify Original List

Algorithm

  • Step 1 ? Define a function remove_occurrences_inplace() that takes the nested list and target value.

  • Step 2 ? Iterate through the list in reverse order to avoid index shifting issues.

  • Step 3 ? If the item is a list, recursively call the function on its sublists.

  • Step 4 ? If the element matches the target element, use the del keyword to remove it.

  • Step 5 ? Return the modified list.

Example

def remove_occurrences_inplace(nested_list, target):
    # Iterate in reverse to avoid index shifting issues
    for i in range(len(nested_list) - 1, -1, -1):
        element = nested_list[i]
        if isinstance(element, list):
            remove_occurrences_inplace(element, target)
        elif element == target:
            del nested_list[i]
    return nested_list

# Test the function
nested_list = [1, [2, 3, 2], [4, [5, 2, 6]], 2]
target = 2
print("Original list:", nested_list)
output = remove_occurrences_inplace(nested_list, target)
print("After removing", target, ":", output)
Original list: [1, [2, 3, 2], [4, [5, 2, 6]], 2]
After removing 2 : [1, [3], [4, [5, 6]]]

Approach 3: Using List Comprehension with Recursion

This approach combines the power of list comprehension with recursion for a more Pythonic solution ?

def remove_occurrences_comprehension(nested_list, target):
    return [
        remove_occurrences_comprehension(element, target) if isinstance(element, list) 
        else element for element in nested_list if element != target
    ]

# Test the function
nested_list = [1, [2, 3, 2], [4, [5, 2, 6]], 2, [2, [2, 7]]]
target = 2
output = remove_occurrences_comprehension(nested_list, target)
print("Original list:", nested_list)
print("After removing", target, ":", output)
Original list: [1, [2, 3, 2], [4, [5, 2, 6]], 2, [2, [2, 7]]]
After removing 2 : [1, [3], [4, [5, 6]], [[7]]]

Comparison

Method Modifies Original Memory Usage Best For
New List Creation No Higher When original list must be preserved
In-place Modification Yes Lower Memory-efficient operations
List Comprehension No Higher Pythonic, concise code

Conclusion

We explored three different approaches to removing all occurrences in nested lists: creating new lists, in-place modification, and using list comprehension with recursion. Choose the approach based on whether you need to preserve the original list and your memory constraints. All methods effectively handle deeply nested structures through recursion.

Updated on: 2026-03-27T13:44:08+05:30

481 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements