Need to understand Python generator object
Asked Answered
L

4

6

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.

Laellaertes answered 26/7, 2012 at 15:27 Comment(0)
B
14

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.

Browning answered 26/7, 2012 at 15:30 Comment(2)
I don't think you pasted the link you meant to.Quartering
@interjay: good catch, c&p failure. Anyone else enjoy set-lists of Norwegian festival concerts? :-P Corrected.Browning
E
2

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.

Elswick answered 26/7, 2012 at 15:30 Comment(0)
H
2

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.

Handedness answered 26/7, 2012 at 15:30 Comment(1)
doesn't really answer the question.Curlicue
E
1

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.

Enroll answered 26/7, 2012 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.