Why do lambdas defined in a loop with different values all return the same result?

0 votes

Why do lambdas defined in a loop with different values all return the same result? I am unable to understand the logic here.

Example:

squares = []
for x in range(5):
    squares.append(lambda: x**2)
Jul 24, 2019 in Python by Laksha
40 views

1 answer to this question.

0 votes

Here x is not local to the lambda but is defined outside the scope and is only accessed when the lambda is called rather than when defined. At the end of the loop, the value of x is 4 and hence returns only 16 for all values.

save the values in variables local to the lambdas. something like this:

squares = []
for x in range(5):
    squares.append(lambda n=x: n**2)

answered Jul 24, 2019 by Haseeb

Related Questions In Python

0 votes
1 answer

How do I run a set of code for all the requests in Flask?

Hi, You can use dedicated hooks(decorators) called before ...READ MORE

answered Jun 20, 2019 in Python by Shabnam
• 920 points
55 views
0 votes
1 answer
+2 votes
3 answers

Write a for loop that prints all elements of a list and their position in the list. a = [4,7,3,2,5,9]

Try using this question by list comprehension: a=[4,7,3,2,5,9] print([x for ...READ MORE

answered Dec 8, 2019 in Python by vinaykumar
• 160 points
2,213 views
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 771 views
0 votes
0 answers
+4 votes
6 answers
0 votes
2 answers

Why do we use return statement in python?

def maximum(x, y):     if x > y:     ...READ MORE

answered Apr 4, 2019 in Python by anonymous
105 views
0 votes
1 answer

How can I lookup hostname using the IP address with a timeout in Python?

Good question. I actually was stuck with ...READ MORE

answered Feb 6, 2019 in Python by Nymeria
• 3,540 points
191 views