Remove Element in Python

Removing elements from a list is a common operation in Python. When we need to remove all instances of a specific value in-place and return the new length, we can use a two-pointer approach that modifies the original list efficiently.

The problem: given a list nums and a value val, remove all instances of val in-place and return the new length of the modified list.

Algorithm Steps

To solve this problem, we follow these steps ?

  • Initialize count = 0 (tracks position for valid elements)

  • For each element in the list ?

    • If the element is not equal to val ?

      • Place it at position count

      • Increment count

  • Return count (new length)

Implementation

Here's the complete solution using the two-pointer technique ?

class Solution:
    def removeElement(self, nums, val):
        count = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[count] = nums[i]
                count += 1
        return count

# Test the solution
ob = Solution()
nums = [0, 1, 5, 5, 3, 0, 4, 5]
result = ob.removeElement(nums, 5)
print(f"New length: {result}")
print(f"Modified list: {nums[:result]}")
New length: 5
Modified list: [0, 1, 3, 0, 4]

Alternative Approach Using Built-in Methods

For simpler cases, you can use list comprehension or built-in methods ?

def remove_element_builtin(nums, val):
    # Using list comprehension
    filtered = [x for x in nums if x != val]
    return len(filtered), filtered

# Test the alternative approach
nums = [0, 1, 5, 5, 3, 0, 4, 5]
length, filtered_list = remove_element_builtin(nums, 5)
print(f"New length: {length}")
print(f"Filtered list: {filtered_list}")
New length: 5
Filtered list: [0, 1, 3, 0, 4]

How It Works

The two-pointer approach works by maintaining two positions:

  • Read pointer (i): Scans through all elements

  • Write pointer (count): Points to where valid elements should be placed

When we encounter an element that's not equal to val, we copy it to the write position and increment the write pointer. This effectively "compacts" the array by removing unwanted elements.

Comparison

Method Space Complexity Modifies Original Best For
Two-pointer O(1) Yes In-place modification
List comprehension O(n) No Creating new list

Conclusion

The two-pointer approach efficiently removes elements in-place with O(1) extra space and O(n) time complexity. Use list comprehension when you need a new list, or the in-place method when memory efficiency is important.

Updated on: 2026-03-25T08:44:48+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements