Home > Software engineering >  How to remove an element from a list x amount of times?
How to remove an element from a list x amount of times?

Time:03-09

I want to remove a number by an x amount of times from a list. For example, for this list [1, 4, 3, 6, 4, 3, 2, 4, 8, 11] if I wanted to remove the integer 4 by 2 times, the list would look like this: [1, 3, 6, 3, 2, 4, 8, 11]. What code would be efficient in this situation? The code I have in the moment:

int_list = [1, 4, 3, 6, 4, 3, 2, 4, 8, 11]
result = []
remove = int(input('remove: '))
times = int(input('times: '))
for i in int_list:
    if i != remove:
        result.append(i)
elements = result
print(elements)

CodePudding user response:

Working in-place

The list method remove removes the first occurrence of the argument from the list. So you can simply call it x amount of times on the list:

int_list = [1, 4, 3, 6, 4, 3, 2, 4, 8, 11]
remove = 4
times = 2
for _ in range(times):
    int_list.remove(remove)
print(int_list)

Will give:

[1, 3, 6, 3, 2, 4, 8, 11]

Handling errors

In case the element is not found, remove will raise an error. If you want to avoid that:

  • Check the input pre-hand by making sure there are enough elements to remove using the count method:

    if int_list.count(remove) <= times:
       # rest of code
    
  • If you want to just remove all possible elements, add a check before the remove call:

    for _ in range(times):
        if remove in int_list:
            int_list.remove(remove)
    

Returning a new list

You can of course simply create a copy of the input list (res = int_list.copy()) and then apply the in-place solution from above. Otherwise, to create a completely new list, use times as a counter for how many times to "skip" the wanted number:

int_list = [1, 4, 3, 6, 4, 3, 2, 4, 8, 11]
remove = 4
times = 2
res = []
for num in int_list:
    if num == remove and times > 0:
        times -= 1
        continue
    res.append(num)
print(res)

In this case there is no error handling to make. We are simply ignoring the required element a given amount of times. If it doesn't exist at all, less, or more times than given - nothing will happen.

  • Related