This is a question about indexing the Python list

Asked 2 years ago, Updated 2 years ago, 14 views

class namecard:
    def __init__(self, name, email, addr):
        self.name = name
        self.email = email
        self.addr = addr

    def printinfo(self):
        print("="*30)
        print("Name: "+self.name)
        print("Email: "+self.email)
        print("Address: "+self.addr)

        print("=" * 30)


list = []

def run():

    print('')
    print("name: ")
    name = input()
    print("email: ")
    email = input()
    print("arrd: ")
    addr = input()

    list.append(namecard(name, email, addr))
    print('')
    print('')
    print('')


while True:
    print("="*30)
    print ("1. Add Business Card")
    print ("2. Business Card List")
    print ("3. Clear Business Card")
    print("4. Exit")

    print("=" * 30)

    print("Select: ")

    select = int(input())
    if select == 1:
        run()
    elif select == 2:
        for i in range(len(list)):
            list[i].printinfo()
            print('')
            print('')

    elif select == 3:
        print("Whose business card should I erase?": ")
        removename = input()

        for i in range(len(list)):
            if removename == list[i-1].name:
                del list[i-1]
    elif select == 4:
        break
    else:
        continue



I'm making a program where you can add business cards, look at them, and erase them A class is added to the list and when viewing the list

for i in range(len(list)):
            list[i].printinfo()

It's accessible with this index (and it seems to fit my intuition)

But when I deleted my business card, I tried many times and found it

for i in range(len(list)):
    if removename == list[i-1].name:

You have to do i-1 like this. It's the same way, but why can I access it with i-1 when I erase it?

python

2022-09-21 20:13

1 Answers

It's right to access the list with i. If you follow the code above, there is a bug that cannot be deleted because the last value of the list cannot be accessed.

If you change i-1 to i, the reason why it doesn't go back is because the list index out of range error comes out. This is because the number of list values decreases as soon as del clears one list value, so there is no list value to refer to in the last loop statement.

After fixing i-1 to i, add braek after del statement, or find the list value number that needs to be erased inside the loop statement and erase it with del outside the loop statement.


2022-09-21 20:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.