if/if any in a list comprehension
What is the difference between if / if any in a list comprehension?
return [word for word in words if any(set(word.upper()) <= set(row) for row in ('QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM'))]
gives me the expected result. However, if I use "if" instead of "if any", then the result is wrong.
(set(word.upper()) <= set(row) for row in ('QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM'))is a generator expression.
ifwill always see this as a
anyis a function. It iterates over the generator expression and returns a bool
There is no "if any" it's "if [some expression]" the
anyis part of the expression
Think of it this way. The
anymethod will return
Truethe moment it meets the condition you are looking for as it iterates over the collection. In other words it 'short circuits' once it meets your condition.
So, inside your
anyyou are determining this
Truecondition. Once you move outside of it, the
ifin the overall comprehension is simply checking for whether the
anydid in fact return
True. In the event it is
Truecheck), you take the
wordin to the list you are crafting.