简体   繁体   中英

Need to understand Python generator object

In the following:

name = 'TODD'
chars = set('AEIOU')
for ii in range(-1, int(math.copysign(len(name) + 1, -1)), -1):
    if any((cc in chars) for cc in name[ii]):
        print 'Found'
    else:
        print 'Not Found'

I understand that what's inside any(...) is a generator object. What I don't understand is the lack of parentheses - if the parentheses belong to the any() function, shouldn't there be another set of parentheses around the generator expression?

Thanks.

The parenthesis can be omitted when used in function calls with only one argument, the generator expression syntax specifically allows for it.

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.

You can leave out the parentheses of a generator expression if the expression is the only thing in parentheses already.

From the documentation :

The parentheses can be omitted on calls with only one argument.

No, the extra parens are not needed, nor in fact are parens always necessary for the "Boolean expression" you are testing, see these two simple examples:

In [37]: any(i > 10 for i in range(19))
Out[37]: True

In [38]: all(i > 10 for i in range(19))
Out[38]: False

What you have is a function call with a single argument (your generator expression) so no parens are required. See the generator expressions docs for more information.

For function calls with just one argument (that generator expression), they aren't required per the docs

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM