I often see code similar to this:
return [(var, val) for val in self.domains[var]
if self.nconflicts(var, val, assignment) == 0]
and I’m like DAMN that’s sexy. But then I try to drop it sometimes and I get syntax errors. Are there any particular rules for this nice form of code writing that reverses the typical placement of for and if statements?
They’re called list comprehensions. The basic syntax is (I’m using parens to group my words, not as part of the syntax):
If the
conditionevaluates to true, the resulting list includes the(expression involving x). So, for example, the following list comprehension uses this to only include strings in the resulting list.Note that the
ifpart is optional, and theexpression involving xcan be as simple as justx(often used when you are just filtering out elements from another list).In fact, the
expression involving xdoesn’t really have to havexin it at all. For example, if for some reason you wanted a list of0‘s as long as your name you could do this:For when you don’t need the list to stick around after you make it, use generator expressions instead. (Generator expressions and list comprehensions have the same syntax.)