23

I want to determine if a list contains a certain string, so I use a generator expression, like so:

g = (s for s in myList if s == myString)
any(g)

Of course I want to inline this, so I do:

any((s for s in myList if s == myString))

Then I think it would look nicer with single parens, so I try:

any(s for s in myList if s == myString)

not really expecting it work. Surprise! it does!

So is this legal Python or just something my implementation allows? If it's legal, what is the general rule here?

Ari
  • 3,460
  • 3
  • 24
  • 31

2 Answers2

23

It is legal, and the general rule is that you do need parentheses around a generator expression. As a special exception, the parentheses from a function call also count (for functions with only a single parameter). (Documentation)

Note that testing if my_string appears in my_list is as easy as

my_string in my_list

No generator expression or call to any() needed!

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Thanks for the answer. `my_string in my_list` was the first thing I tried, but it failed to find a string that was present. I concluded that it was doing object comparison rather than value comparison, which is what I need. I'll check again. – Ari Feb 15 '12 at 17:09
  • 1
    @Ari: No, it does value comparison. I don't know what went wrong in your case. – Sven Marnach Feb 15 '12 at 17:12
3

It's "legal", and expressly supported. The general rule is "((x)) is always the same as (x)" (even though (x) is not always the same as x of course,) and it's applied to generator expressions simply for convenience.

Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
  • 3
    Just to clarify, `x` is not a place holder for just anything here. `f((a, b))` is of course different from `f(a, b)`. – Sven Marnach Feb 15 '12 at 17:13
  • 1
    Yes, indeed, it's a placeholder for a single expression. – Thomas Wouters Feb 15 '12 at 17:21
  • Can you provide a reference for this rule (that ((x)) is always the same as (x) )? – Ari Feb 15 '12 at 17:21
  • 2
    @Ari: See [here](http://docs.python.org/reference/expressions.html#grammar-token-parenth_form): "A parenthesized expression list yields whatever that expression list yields." This usually doesn't apply to the parens in function calls, though -- it is a special exception for generator expressions. – Sven Marnach Feb 15 '12 at 17:27