Sabuncu
Sabuncu

Reputation: 5264

Trying to understand Python code with generator expression

In the following code:

chars = set('AEIOU')
...
if any((cc in chars) for cc in name[ii]):
    print 'Found'

What is the "(cc in chars)" part? I know that it is applied to each cc that is generated by the for loop. But is the "(cc in chars)" construct itself a generator expression?

Thanks.

Upvotes: 1

Views: 126

Answers (3)

FRD
FRD

Reputation: 2254

No, the (cc in chars) is merely a boolean that returns True if cc is in chars and False otherwise.

In fact, the code could actually be written

chars = set('AEIOU')
...
if [cc for cc in name[ii] if cc in chars]:
    print 'Found'

In that case, if the list has any elements (making it pass the if-clause), that's because some cc is in chars. I'd actually find that to be more readable and straightforward. Cheers.

EDIT:

To clarify my answer, [cc for cc in name[ii] if cc in chars] generates a list of all characters in name[ii] that in 'chars' (in that case, vowels). If this list has any elements on it, it'll pass the if-test.

[cc for cc in name[ii] if cc in chars] says "for each element/character in name[ii], add it only if it's in chars. Check out this answer for clarification.

Upvotes: 1

Sam Mussmann
Sam Mussmann

Reputation: 5983

(cc in chars) simply checks if the string cc is contained in chars and returns a boolean false or true.

According to the Python Language Reference, something in-between parentheses is not a generator expression unless it has at least one for i in iterable clause.

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121804

No, the (cc in chars) part is a boolean expression; in is a sequence operator that tests if cc is a member of the sequence chars. The parenthesis are actually redundant there and could be omitted.

Upvotes: 3

Related Questions