Generator Expressions vs. List Comprehension

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

    The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.

    For example:

    sum(x*2 for x in xrange(256))
    
    dict( (k, some_func(k)) for k in some_list_of_keys )
    

    The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)

    You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.

    For example:

    reversed( [x*2 for x in xrange(256)] )
    

提交回复
热议问题