foo = [x for x in bar if x.occupants > 1]
After googling and searching on here, couldn\'t figure out what this does. Maybe I wasn\'t searching
It's a list comprehension
foo
will be a filtered list of bar
containing the objects with the attribute occupants > 1
bar
can be a list
, set
, dict
or any other iterable
Here is an example to clarify
>>> class Bar(object):
... def __init__(self, occupants):
... self.occupants = occupants
...
>>> bar=[Bar(0), Bar(1), Bar(2), Bar(3)]
>>> foo = [x for x in bar if x.occupants > 1]
>>> foo
[<__main__.Bar object at 0xb748516c>, <__main__.Bar object at 0xb748518c>]
So foo has 2 Bar
objects, but how do we check which ones they are? Lets add a __repr__
method to Bar
so it is more informative
>>> Bar.__repr__=lambda self:"Bar(occupants={0})".format(self.occupants)
>>> foo
[Bar(occupants=2), Bar(occupants=3)]