list comprehension filtering - “the set() trap”

前端 未结 5 1302
野性不改
野性不改 2020-11-30 04:16

A reasonably common operation is to filter one list based on another list. People quickly find that this:

[x for x in list_1 if x          


        
5条回答
  •  [愿得一人]
    2020-11-30 04:50

    The basic reason is that a literal really can't change, whereas if it's an expression like set(list_2), it's possible that evaluating the target expression or the iterable of the comprehension could change the value of set(list_2). For instance, if you have

    [f(x) for x in list_1 if x in set(list_2)]
    

    It is possible that f modifies list_2.

    Even for a simple [x for x in blah ...] expression, it's theoretically possible that the __iter__ method of blah could modify list_2.

    I would imagine there is some scope for optimizations, but the current behavior keeps things simpler. If you start adding optimizations for things like "it is only evaluated once if the target expression is a single bare name and the iterable is a builtin list or dict..." you make it much more complicated to figure out what will happen in any given situation.

提交回复
热议问题