1

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.

Sabuncu
  • 5,095
  • 5
  • 55
  • 89

3 Answers3

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

(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.

Sam Mussmann
  • 5,883
  • 2
  • 29
  • 43
1

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.

Community
  • 1
  • 1
FRD
  • 2,254
  • 3
  • 19
  • 24