Search code examples
pythonpython-3.xsyntax-errorany

'any' doesn't raise error?


I was playing around then I noticed this:

>>> l = input().split()
1 25 11 4
>>> any(s == s[::-1] for s in l)
True
>>> s == s[::-1] for s in l
SyntaxError: invalid syntax
>>> 

Why does any(s == s[::-1] for s in l) work if s == s[::-1] for s in l itself would raise error?


Solution

  • any(s == s[::-1] for s in l)
    

    is the same as:

    any((s == s[::-1] for s in l))
    

    and:

    (s == s[::-1] for s in l)
    

    is not a syntax error. It is a generator expression. As you have found parenthesis are required around generator expressions except when they occur as the only argument to a function call.