Search code examples
pythondictionaryfilterpython-itertools

Python, Filter a List of Objects, but return a specific attribute?


Suppose I have a list of Person objects, which have an age and room_number attribute, and I have written a check() function, which returns True, if person.age() and person.room_number() are satisfactory, False otherwise.

filter(check, list_of_people_objects) would return a list of Person objects which satisfies the criteria of check()

However, my question is, is there a way of returning a list of each approved Person's room number without iterating through the list twice, like so without using list comprehension? So filtering, but returning a more specific attribute of the iterable.

map(lambda x: x.room_number(), filter(check, list_of_people_objects))


Solution

  • There are in fact two ways.

    1. itertools

      map(..., itertools.ifilter(..))
      
    2. List comprehension

      [x.room_number() for x in people if check(x)]
      

    Which you choose is mostly a matter of taste, but convention leans towards the latter.