'Lazy evaluation when use lambda and list comprehension [duplicate]

Here is the example python code.

f_list = [lambda x : x ** i for i in range(5)]
[f_list[j](10) for j in range(5)]

I thought the output would be:

[1, 10, 100, 1000, 10000]

But I got this instead:

[10000, 10000, 10000, 10000, 10000]

I'm wondering what actually happened when I run this code. And what's the connections with lazy evaluation.



Solution 1:[1]

Here is a good example of why curryfying is good, you can achieve your goal currying your function like this:

f_list = [(lambda y : lambda x : x ** y)(i) for i in range(5)]
r = [f_list[j](10) for j in range(5)]

The result will be:

=> [1, 10, 100, 1000, 10000]

Currying:

The simple way to understand what curry is for me is the next one, instead of give to a function all the parameters it needs, you create a function, that always receives one parameter, and returns another function that takes again one parameter, and in the final function, you do the transformation you need with all the parameters

A little example:

sum_curry = lambda x : lambda y : x + y

here you've got a simple sum function, but imagine you want to have the function plus_one, ok, yuu can reuse the function above like this:

plus_one = sum_curry(1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1