Generator Expressions vs. List Comprehension

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

    Python 3.7:

    List comprehensions are faster.

    Generators are more memory efficient.

    As all others have said, if you're looking to scale infinite data, you'll need a generator eventually. For relatively static small and medium-sized jobs where speed is necessary, a list comprehension is best.

提交回复
热议问题