Reputation: 171
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?
Upvotes: 0
Views: 65
Reputation: 2890
To complete Dan D. answer,
(s == s[::-1] for s in l)
is like :
def your_function():
for s in l:
yield s == s[::-1]
Upvotes: 1
Reputation: 74655
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.
Upvotes: 3