I am new to python and I am trying to understand the logic here:
What does lambda x=x mean? in the complete function below:
tables = [lambda x=x: x*10 for x in range(1, 11)]
for table in tables:
print(table())
I am new to python and I am trying to understand the logic here:
What does lambda x=x mean? in the complete function below:
tables = [lambda x=x: x*10 for x in range(1, 11)]
for table in tables:
print(table())
There are two different variables named x here.
The first one is the parameter, which is a local variable in the function being defined.
The second is a variable visible in the scope where the function is being defined. Its value is stored as the default value to use for the first variable x if no argument is passed when the function is called.
It is far less confusing if you just use two different names for the two different variables:
tables = [lambda x=y: x*10 for y in range(1, 11)]
This is the short way of writing
tables = []
tables.append(lambda x=1: x*10)
tables.append(lambda x=2: x*10)
# etc.
Based on how each function is called in the following loop, the intention appears to be to never actually pass an argument when the function is called, and that what we really want is to automate something like
tables = []
tables.append(lambda : 1 * 10)
tables.append(lambda : 2 * 10)
# etc.
The naive approach
tables = [lambda: x*10 for x in range(1, 11)]
fails because x is a free variable in the body of the function; it does not get replaced with the value of x at the time the function is called. Doing this, you end up with a list of 10 identical function, all of which depend on the last value assigned to x before the function is called.
By binding a default value that is evaluated immediately to the parameter, you "inject" the current value of x into the function right away, so that you end up with a list of 10 different functions.
tables = [lambda y = x: x*10 for x in range(1, 11)] for table in tables: print(table()) The output is 10 100s printed one below the other I an unable to understand the logic