[Python] Using filter function and convert the iterator produce to a list [closed]

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    Here is something I stumbled upon. I have this little class.

    from functools import reduce

    class CourseAttempt:
    def __init__(self, course_name: str, grade: int, credits: int):
    self.course_name = course_name
    self.grade = grade
    self.credits = credits

    def __str__(self):
    return f"{self.course_name} ({self.credits} cr) grade {self.grade}"


    Then these two code snippets

    course_passed = list(filter(lambda x: x.grade >= 1, attempts))
    print(course_passed)


    and

    course_passed = filter(lambda x: x.grade >= 1, attempts)
    course_passed_list = list(course_passed)
    print(course_passed_list)


    I'm trying to filter a list of students called 'attempts' with grade >= 1 then convert the iterator produced by the filter function into a list before printing. The first code snippet does exactly what I want meanwhile the second do not. Can anyone explain to me why these two operation do no produce the same result?

    Continue reading...

Compartilhe esta Página