if/if any in a list comprehension

What is the difference between if / if any in a list comprehension?

The code:

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.

2 answers

  • answered 2018-02-13 02:55 John La Rooy

    (set(word.upper()) <= set(row) for row in ('QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM')) is a generator expression. if will always see this as a True value

    any is a function. It iterates over the generator expression and returns a bool

    There is no "if any" it's "if [some expression]" the any is part of the expression

  • answered 2018-02-13 02:55 idjaw

    Think of it this way. The any method will return True the 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 any you are determining this True condition. Once you move outside of it, the if in the overall comprehension is simply checking for whether the any did in fact return True. In the event it is True (aka the if passed the True check), you take the word in to the list you are crafting.