-2

I'm having a hard time with my delContact method because I want to delete the object which is similar to delVar but I don't know how to I've tried all = None or del all. but when I a call the show method/function after the delContact(), the value that I wanted to delete still shows

class Phonebook:

    def __init__(self,name,type,email,phone):

        self.name = name
        self.type = type
        self.email = email
        self.phone = phone

        print('Adding {} as a Contact with an email of {} and a phone number of {}'.format(self.name,self.email,self.phone))

    def tell(self):

        print('Name: {} | Type: {} | Email: {} | Phone: {}'.format(self.name,self.type,self.email,self.phone))

    def retName(self):

        return  self.name

All = []

def addContact():
    name = input('Enter your the name please: ')
    type = input('Enter the type of the Contact Please: ')
    email = input('Enter the the email of the Contact Please: ')
    phone = input('Enter the Phone number of the Contact Please: ')

    merge = Phonebook(name,type,email,phone)

    All.append(merge)

def show():

    for all in All:
        all.tell()

def delContact():

    show()

    delVar = input('Enter the name you want to delete: ')

    for all in All:

        if all.retName() == delVar:
            print(all.retName())
            all = ''
        else:
            continue



addContact()
addContact()
show()
delContact()
show()
Cœur
  • 37,241
  • 25
  • 195
  • 267
Alpha_Bords
  • 425
  • 1
  • 4
  • 11

1 Answers1

2

Here:

for all in All:
    if all.retName() == delVar:
        print(all.retName())
        all = ''

you are not deleting anything, you are just rebinding the local name all to the empty string. To delete the item from the list, you would have to use All.remove(item):

for all in All:
    if all.retName() == delVar:
        All.remove(all)
        break

Note that if you have more than one item with the same name, this will only remove the first one...

Also note that modifying a list you're iterating upon can lead to unexpected results. It's safe in this case since we immediatly break out of the loop but it's usually something to avoid.

Another solution which is safer and will remove all matching items is to filter out the list and replace the original with the result:

All[:] = [item for item in All if item.name != delVar]

Oh and yes too, your retName method is totally useless, name is a public attribute of your class.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118