Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find youngest member of a list of people

I’m learning Python right now and I have a problem with finding the youngest one in my list.

class ember :
    def __init__(self,name,age,sex,weight,):
        self.name = str(name)
        self.age = int(age)
        self.sex = str(sex)
        self.weight = int(weight)

e1=ember("Pisti1", 13, "Ferfi", 45)
e2=ember("Pisti2", 14, "Ferfi", 46)
e3=ember("Pisti3", 15, "Ferfi", 120)
e4=ember("Pisti4", 16, "Ferfi", 48)
e5=ember("JÚLYA", 17, "Nő", 89)

Lista=[]
Lista.append(e1)
Lista.append(e2)
Lista.append(e3)
Lista.append(e4)
Lista.append(e5)



maxx=1000000000000
for x in Lista:
    if x.age>maxx:
        maxx=x.age
print (x.name, x.age)

It only gives me the oldest (last) one in the list (JÚLYA).

I watched a couple of videos and tutorials about lists and list comprehensions but I don’t get it; can someone give me a "hint" or help me?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to finding the minimum by a certain attribute. The standard way to do this in Python is (after putting import operator at the start of your code)

youngest = min(Lista, key=operator.attrgetter("age"))
print(youngest.name, youngest.age)

Note that the middle section of your code (e1=.append(e5)) can be more concisely expressed as follows.

Lista = [
    ember("Pisti1", 13, "Ferfi", 45),
    ember("Pisti2", 14, "Ferfi", 46),
    ember("Pisti3", 15, "Ferfi", 120),
    ember("Pisti4", 16, "Ferfi", 48),
    ember("JÚLYA", 17, "Nő", 89),
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading