I have a list of objects. I would like to check some string if that string exists as a field value any object in the list. for example,

class Ani:
    name = ''
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name


animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')

a = [animal1, animal2, animal3,animal4,animal5]

my problem to write a code in order to see if there is an object with given name. for example "chip".

4 Answers

3
Shuvojit On

You can iterate over the array of objects, and check with each object's getName function.

class Ani:
    name = ''
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name


animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')

animals = [animal1, animal2, animal3,animal4,animal5]

searched_animal = 'rex'

for animal in animals:
  if animal.getName() == searched_animal:
    print('Found')
    break
3
Netwave On

You can use any plus a comprehension:

any(animal.getName() == "chip" for animal in animals)
0
Karthik Vg On

You can use the getName method present in Ani class for this program

class Ani:
    name = ''
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name


animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')

animals = [animal1, animal2, animal3,animal4,animal5]

key = 'chip'

flag=0
for animal in animals:
    if animal.getName() == key:
        print('Found')
        flag=1
        break

if flag==0:
    print("Not Found")
0
Community On

Iterating a list containing anything is quite simple really. Like so:

animal_to_find = "someAnimal"
for animal in animals:
  if animal.getName() == animal_to_find:
    print("Found a match for: " + animal)