Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python generator expression parentheses oddity

Tags:

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?

like image 601
Ari Avatar asked Feb 15 '12 16:02

Ari


1 Answers

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!

like image 63
Sven Marnach Avatar answered Sep 28 '22 10:09

Sven Marnach