Generator Expressions vs. List Comprehension

前端 未结 9 1785
梦如初夏
梦如初夏 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:15

    Iterating over the generator expression or the list comprehension will do the same thing. However, the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.

提交回复
热议问题