Jen
Jen

Reputation: 255

Trying to remove multiples of the same number in Python

I'm trying to remove numbers from a list that are the same. So if I have 1,2,3,4,5,3 and I tell it to remove 3, it will only remove the first one (using .remove) to give me 1,2,4,5,3. I now know that .remove is only supposed to remove the first one, so my question is, what other method can I use? I've tried .pop and del but neither seem to do all of them (though I could have been doing it wrong). I would have just made a new list without the repeating number but it's meant to go through my teachers driver so I can't just make up a new list (or at least, I'm assuming there's any easier way?) In case it helps, here's that part of the code so far:

    def remove_element(self,integer):
        self.integer = integer
        self.members.remove(integer)

Upvotes: 2

Views: 1109

Answers (5)

Mingyu
Mingyu

Reputation: 33379

You could use the built-in filter, and you don't have to write a method for it:

>>> l = [1, 2, 3, 4, 5, 3]
>>> filter(lambda f: f != 3, l)
[1, 2, 4, 5]

In the code above, we define a lambda function lambda f: f != 3, which test if an element in the list is 3 or not. In your case, you might use self.integer to replace 3.

If you are not familiar with lambda function, lambda f: f != 3 is equivalent to the function foo:

>>> def foo(f):
...     return f != 3

Upvotes: 2

user2357112
user2357112

Reputation: 281586

def without_element(l, element):
    return [item for item in l if item != element]

def remove_all(l, element):
    try:
        while True:
            l.remove(element)
    except ValueError:
        pass

The first function makes a new list without any copies of the element you don't want. The second removes all copies from the existing list. There's no "remove all copies" method; usually, if you want that, you're using the wrong data structure. Are you sure you should be using a list?

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114038

def remove_element(self,integer):
    while integer in self.members:
          self.members.remove(integer)

Upvotes: 0

sampson-chen
sampson-chen

Reputation: 47317

list comprehension, e.g:

[x for x in a_list if x != integer]

So in your case it would be:

def remove_element(self,integer):
    self.integer = integer
    self.members = [elem for elem in self.members if elem != integer]

Upvotes: 1

arshajii
arshajii

Reputation: 129537

You can use a list comprehension:

>>> l = [1,2,3,4,5,3]
>>> 
>>> [i for i in l if i != 3]
[1, 2, 4, 5]

Just remember that this doesn't actually modify l but instead creates a new list, so be sure to reassign l to the result of the comprehension.

Upvotes: 1

Related Questions