Generator Expressions vs. List Comprehension

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

    Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.

    See Generator expressions and list comprehensions for more info.

提交回复
热议问题