Returning people born before certain year from tuple?

Question:

I need to write a function named older_people(people: list, year: int), which selects all those people on the list who were born before the year given as an argument. The function should return the names of these people in a new list.

An example of its use:

p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p4 = ("Ernest", 1997)
people = [p1, p2, p3, p4]

older = older_people(people, 1979)
print(older)

Sample output:
[ ‘Adam’, ‘Mary’ ]

So far I got:

    def older_people(people: list, year: int):

        for person in plist:
            if person[1] < year:
                return person[0]
 



    p1 = ("Adam", 1977)
    p2 = ("Ellen", 1985)
    p3 = ("Mary", 1953)
    p4 = ("Ernest", 1997)
    plist = [p1, p2, p3, p4]

    older = older_people(plist, 1979)
    print(older)

At the moment this just prints the first person (Adam) who is born before 1979.
Any help for this one?

Asked By: Fontana dot py

||

Answers:

First you should use the argument of the function in the body of older_people instead of the global variable plist. people should be used instead of plist.

Then, your return statement is inside the for loop, this means that it will leave the function at the first time the if condition is true, hence printing only one person.

def older_people(people: list, year: int):
    result = []
    for person in people:
        if person[1] < year:
         result.append(person[0])
    return result




p1 = ("Adam", 1977)
p2 = ("Ellen", 1985)
p3 = ("Mary", 1953)
p4 = ("Ernest", 1997)
plist = [p1, p2, p3, p4]

older = older_people(plist, 1979)
print(older)
Answered By: robinood

Alternately you could reference both elements of the tuple with labels instead of by index, also list comprehension…

def older_people(people: list, year: int):
    return [person for person, birth_year in people if birth_year <= year]
Answered By: Amos Baker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.