Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove a object in a python list

Tags:

python

I create a class named point as following:

class point:
    def __init__(self):
        self.x = 0
        self.y = 0

and create a list of point instances:

p1 = point()
p1.x = 1
p1.y = 1
p2 = point()
p2.x = 2
p2.y = 2
p_list = []
p_list.append(p1)
p_list.append(p2)

Now I'd like remove from the list the instance which x = 1 and y = 1, how can I do this?

I try to add a __cmp__ method for class point as following:

class point:
    def __init__(self):
        self.x = 0
        self.y = 0    
    def __cmp__(self, p):
        return self.x==p.x and self.y==p.y

But the following code does not work

r = point()
r.x = 1
r.y = 1
if r in p_list:
    print('correct')
else:
    print('wrong') # it will go here
p_list.remove(r) # it reports 'ValueError: list.remove(x): x not in list'
like image 773
Deng Haijun Avatar asked Apr 01 '16 15:04

Deng Haijun


People also ask

How do I remove an object from a list?

There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.

Can you remove items from lists in Python?

In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.

How do you remove an object from a set in Python?

Python Set remove() MethodThe remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.


1 Answers

Your __cmp__ function is not correct. __cmp__ should return -1/0/+1 depending on whether the second element is smaller/equal/greater than self. So when your __cmp__ is called, it returns True if the elements are equal, which is then interpreted as 1, and thus "greater than". And if the elements are non-equal, it returns False, i.e. 0, which is interpreted as "equal").

For two-dimensional points, "greater than" and "smaller than" are not very clearly defined, anyway, so you can just replace your __cmp__ with __eq__ using the same implementation. Your point class should be:

class point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y    

    def __eq__(self, p):
        return self.x==p.x and self.y==p.y
like image 113
tobias_k Avatar answered Oct 19 '22 03:10

tobias_k