Python generator expression parentheses oddity

后端 未结 2 1003
执笔经年
执笔经年 2020-12-15 20:29

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)

相关标签:
2条回答
  • 2020-12-15 20:44

    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!

    0 讨论(0)
  • 2020-12-15 21:01

    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.

    0 讨论(0)
提交回复
热议问题