Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove an element from a list x amount of times?

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading