Baller
Baller

Reputation: 117

Searching from a object attribute in a list full of object

I have created a list filled with class objects. Each object has 5 attributes. I need to search for one specific object using its name only:

def searchword(list):

    name = str(input("Who are you searching for? Please enter name"))

    for i in list:
        if list[i].name == name:
            print("We found him/her. Here is all information we have on him" + str(list[i]))

        else:
            print("Could not be found. Check spelling!")

But I am getting the following error

if list[i].name == name:
    TypeError: list indices must be integers, not Person" 

Person is the class object

Upvotes: 0

Views: 509

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477338

Well if you use:

for i in list:

you no not get a list of indices, you iterate over the persons immediately, so i is a person here. You can thus use:

if i.name == name:

instead of:

if list[i].name == name:

Or in full:

def searchword(list):

    name = str(input("Who are you searching for? Please enter name"))

    for i in list:
        if i.name == name:
            print("We found him/her. Here is all information we have on him" + str(i))

        else:
            print("Could not be found. Check spelling!")

Furthermore you better name your variables more semantically in Python, so:

def searchword(list):

    name = str(input("Who are you searching for? Please enter name"))

    for person in list:
        if person.name == name:
            print("We found him/her. Here is all information we have on him" + str(person))

        else:
            print("Could not be found. Check spelling!")

Upvotes: 1

Related Questions