user11099823
user11099823

Reputation:

Python, remove object from List

I am still learning Python and I have a problem. If my question isn't that clear, please be nice!

Is it possible that while using a list, I can delete an object from the list if only one object matches

So for example:

driver.addDriver(Driver("Ben", "BBB"))                 
driver.removeDriver("Ben", "123")

Can I remove the driver name and print as None while still showing the vehicle number. Thanks.

class Driver:
    def __init__(self, name, vehNo):
        self._name = name
        self._vehNo = vehNo

    @property
    def name(self):
        return self._name

    @property 
    def vehNo(self):
        return self._vehNo
    @vehNo.setter
    def vehNo(self, newVehNo):
        self._vehNo = newVehNo

    def __str__(self):
        return 'Driver Name: {} Vehicle Number: {}'.format(self._name, self._vehNo)


class TransportServices:
    def __init__(self):

    self._drivers   = []



    def searchDriver(self, name = None, vehNo = None):
        for d in self._drivers:
            if d.name == name and d.vehNo == vehNo:
                return d

        return None


#############################################################################

    def addDriver(self, driver):
        d = self.searchDriver(driver.name)
        if d is None:
            self._drivers.append(driver)
            return True
        else:
            return False

#############################################################################

    def removeDriver(self, name = None, vehNo = None):
        d = self.searchDriver(name, vehNo)
        if d is None:
            return False

        else:
            self._drivers.remove(d)



#############################################################################   

    def __str__(self):

        drivers = [str(d) for d in self._drivers]
        return "{} ".format('\n'.join(drivers))



def main():


    driver = TransportServices()
    driver.addDriver(Driver("Alan", "AAA"))
    driver.addDriver(Driver("Ben", "BBB"))
    driver.removeDriver("Ben", "123")



    print(driver)
main()

Upvotes: 0

Views: 207

Answers (1)

Rohitashwa Nigam
Rohitashwa Nigam

Reputation: 408

Basically what you are looking for is not deleting the object but updating it.

You can update the corresponding object as below:

for driver in self.drivers:
    if driver.name == 'Bob': # or  driver vehNo == 'BBB'
        driver.name = None

Also for your case, you could rather use a dictionary which is the same as a hash map in Java.

You can do some thing like below:

self.drivers = {}

self.driver['vehicle Num'] = theDriverObject

so that when you need to access or update you can do it instantly i.e. O(1) without having to loop through all the drivers.

Upvotes: 1

Related Questions