Are list comprehensions syntactic sugar for `list(generator expression)` in Python 3?

前端 未结 4 479
有刺的猬
有刺的猬 2020-12-06 03:54

In Python 3, is a list comprehension simply syntactic sugar for a generator expression fed into the list function?

e.g. is the following code:



        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 04:23

    You can actually show that the two can have different outcomes to prove they are inherently different:

    >>> list(next(iter([])) if x > 3 else x for x in range(10))
    [0, 1, 2, 3]
    
    >>> [next(iter([])) if x > 3 else x for x in range(10)]
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 1, in 
    StopIteration
    

    The expression inside the comprehension is not treated as a generator since the comprehension does not handle the StopIteration, whereas the list constructor does.

提交回复
热议问题