Generator Expressions vs. List Comprehension

前端 未结 9 1800
梦如初夏
梦如初夏 2020-11-21 06:56

When should you use generator expressions and when should you use list comprehensions in Python?

# Generator expression
(x*2 for x in range(256))

# List com         


        
9条回答
  •  执念已碎
    2020-11-21 07:12

    When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:

    >>> mylist = ["a", "b", "c"]
    >>> gen = (elem + "1" for elem in mylist)
    >>> mylist.clear()
    >>> for x in gen: print (x)
    # nothing
    

    If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.

提交回复
热议问题