0

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) 
2
  • 1
    Should it return a new list or manipulate the same one? What would happen if you put, let's say, 8 by 2 times (it only appears once)? Should it be an error? Commented Mar 8, 2022 at 17:15
  • 1
    The only rules are: 1- The code must print a list 2- if times == 0, print original list 3- That's it Commented Mar 8, 2022 at 17:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.