Search code examples
python-3.xlistclasslistobject

remove one object of a class from list of objects


I need to delete an object from the list of objects based on the condition. In the selectDoctor method, I need to remove the object from the list in which its docid is equal to the given id and return the removed list.

class Doctor:
    def __init__(self, docid, docname, deptname):
        self.docid = docid
        self.docname = docname
        self.deptname = deptname

class Hospital:
        def selectDoctor(id,doclist):
        for i in range(0, len(doclist)):
            if doclist[i].docid==id: //in this condition I need to remove that object from list
                doclist.remove(i) //by removing like this it is showing error
        return doclist

for i in range(5):
    docid=int(input())
    docname=input()
    deptname=input()
    doclist.append(Doctor(docid,docname,deptname)

id=int(input())
res=Hospital.selectDoctor(id,doclist)
print(res)

Solution

  • Using list in Python3, it,s easy to achieve this using following statements(you have at least three possibilities):

    • Remove by specifying the item index

    doclist.pop(i)

    OR

    • Remove by specifying the item(s) index(es) (also range of indexes also allowed e.g. del doclist[0:2] for removing first three items of given list) using the keyword del

    del doclist[i]

    • Remove by specifying the item itself

    doclist.remove(doclist[i])

    Reference: https://docs.python.org/3.8/tutorial/datastructures.html

    Feel free to upvote the answer after fixing your error...