Skip to content
Advertisement

Simple Python Issue with Iteration and Lambda

lst = [1, 2, 3]

i = 0
f = lambda x: x * lst[i]

i = 1
print(f(10))
f = lambda x: x * lst[i]

i = 2
print(f(10))
f = lambda x: x * lst[i]

Above is my Python code and I thought it would print out 10, 20, but it says 20, 30. I don’t understand why f is modified by i regardless of the explicit assignment. I’ve got to make it print 10, 20 using an iteration(actually the code is a simplified form of the original one), so it seems that f = lambda x: x * 1 is not allowed.

Advertisement

Answer

i is global variable. so when you call f it uses the current value of i

look at

f = lambda x: x * lst[i]
lst = [1, 2, 3]
for i in range(len(lst)):
    print(f(10))

output

10
20
30

Note, not related to your question, but f = lambda x: x * lst[i] is against PEP8 recommendations:

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier:

Correct: def f(x): return 2*x

Wrong: f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically ‘f’ instead of the generic ”. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement