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.
Answer. In Python, a for loop variable does not have to be initialized beforehand. This is because of how Python for loops work.
The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops.
The reason a lot of for loops start at 0 is because they're looping over arrays, and in most languages (including JavaScript) arrays start at index 0."
For lists, yes, since they are ordered data structures in Python.
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:
result = [] for index in range(len(numbers)): if numbers[index] > 5: result.append(numbers[index]) print result #Prints [12, 34, 67, 37, 9, 81]
result = [] for number in numbers: if number > 5: result.append(number) print result #Prints [12, 34, 67, 37, 9, 81]
result = [number for number in numbers if number > 5]
[function(number) for number in numbers if condition(number)]
where:
function(x)
takes an x
and transforms it into something useful (like for instance: x*x
)condition(x)
returns any False-y value (False, None, empty string, empty list, etc ..) then the current iteration will be skipped (think continue
). If the function return a non-False-y value then the current value makes it to the final resultant array (and goes through the transformation step above).To understand the syntax in a slightly different manner, look at the Bonus section below.
For further information, follow the tutorial all other answers have linked: List Comprehension
(Slightly un-pythonic, but putting it here for sake of completeness)
The example above can be written as:
result = filter(lambda x: x > 5, numbers)
The general expression above can be written as:
result = map(function, filter(condition, numbers)) #result is a list in Py2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With