Lazy evaluation of map

前端 未结 3 691
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 20:02

I recently read that one benefit of map in Python 3 was that it is lazy. That means, it is better to do

map(lambda x: x**2, range(10**100))
         


        
3条回答
  •  隐瞒了意图╮
    2020-12-06 20:25

    There are many benefits; for example, it makes it easier to write memory efficient code.

    def take_up_a_lot_of_memory(*args):
        """
        A contrived example of a function that uses a lot of memory
        """
        return sum([i ** 2 for i in range(10 ** 6)])
    
    megasum = sum(map(take_up_a_lot_of_memory, range(1000)))
    

    Also, sometimes you can terminate a calculation early without iterating through all of the map results, and so avoid redundancy.

提交回复
热议问题