Python for-in loop preceded by a variable

Viewed 132346

I saw some code like:

foo = [x for x in bar if x.occupants > 1]

What does this mean, and how does it work?

5 Answers

Since the programming part of question is fully answered by others it is nice to know its relation to mathematics (set theory). Actually it is the Python implementation of Set builder notation:

Defining a set by axiom of specification:

B = { x є A : S(x) }

English translation: B is a set where its members are chosen from A, so B is a subset of A (B ⊂ A), where characteristic(s) specified by function S holds: S(x) == True

Defining B using list comprehension:

B = [x for x in A if S(x)]

So to build B with list comprehension, member(s) of B (denoted by x) are chosen from set A where S(x) == True (inclusion condition).

Note: Function S which returns a boolean is called predicate.

Related