Greg Flynn Greg Flynn - 2 months ago 25
Python Question

Python for-in loop preceded by a variable

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 the right stuff but here it is. Any input in debunking this shorthand is greatly appreciated.


The current answers are good, but do not talk about how they are just syntactic sugar to some pattern that we are so used to.

Let's start with an example, say we have 10 numbers, and we want a subset of those that are greater than, say, 5.

>>> numbers = [12, 34, 1, 4, 4, 67, 37, 9, 0, 81]

For the above task, the below approaches below are totally identical to one another, and go from most verbose to concise, readable and pythonic:

Approach 1

result = []
for index in range(len(numbers)):
    if numbers[index] > 5:
print result  #Prints [12, 34, 67, 37, 9, 81]

Approach 2 (Slightly cleaner, for-in loops)

result = []
for number in numbers:
    if number > 5:
print result  #Prints [12, 34, 67, 37, 9, 81]

Approach 3 (Enter List Comprehension)

result = [number for number in numbers if number > 5]

or more generally:

[f(number) for number in numbers if "some constraint on number"]

with f(x) some function of the index variable. For further information, follow the tutorial all other answers have linked: List Comprehension


(Slightly un-pythonic, but putting it here for sake of completeness)

result = filter(lambda x: x > 5, numbers)