• Quick note - the problem with Youtube videos not embedding on the forum appears to have been fixed, thanks to ZiprHead. If you do still see problems let me know.

Removing an object from a list in Python

nimzov

Unregistered
Joined
Apr 12, 2004
Messages
954
In Python, I have contructed a list where members of the list are objects.

Now I want to remove a single object from this list.

I can't get a reference to that object.

Here is an example:

PHP:
class  Student(object): # Student object
.......name = ''

.......def __init__(self,  name):   # Constructor
...............self.name    = name

class  Students(object): # Students object (a list of Student)

.......listOfStudent = []

.......def  __init__(self, list):  # Constructor
...............for s in  list:
.....................st = Student(s)  # Construct a Student  object
.....................self.listOfStudent.append(st) # Append to listOfStudent

.......def  removeStudent(self,  aStudent):
...............self.listOfStudent.remove(aStudent)
If I do the following:

s = Students(['Harry', 'Phil', 'Linda'])
p = Student('Phil')
s.removeStudent(p)

It does not work I get the error message: "list.remove(x). x not in list".

The problem seems to arises because the object I construct to put in the list is a different object (even if identical) from the object I construct to remove from the list. So I need a reference to the object already constructed in the list not a reference to an identical object.

Any help will be appreciated.
 
Last edited:

Back
Top Bottom