'How to access a class object inside a list when a value for one of the class attributes is given in Python?
I have a list of class objects and I want to know how can I print a particular class object inside the list given a value for one of its attributes.
Here is my code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
lst = [Person("A",1), Person("B",2), Person("C", 3)]
inputAge = int(input("Age: "))
if inputAge == 2:
print() #this should print the class object with age 2 from the list
I don't know what should I put inside the print()
code.
Solution 1:[1]
This is how you can find the first element of the list having a specific attribute (precondition: all objects of the list have that attribute):
obj = next((x for x in lst if x.age == inputAge), None)
obj
is None
if such an object can't be found in the list.
Once you found the object, you can do whatever you want with it, including printing (print(obj)
).
If you want the printing of the object to be meaningful you would have to do something like this:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'name: ' + self.name + ' age: ' + self.age
This is the complete example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return 'name: ' + self.name + ' age: ' + self.age
lst = [Person("A",1), Person("B",2), Person("C", 3)]
inputAge = int(input("Age: "))
obj = next((x for x in lst if x.age == inputAge), None)
print(obj) # prints the object with age = inputAge
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |