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
1,239 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
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 21, 2019 in Python by Shabnam
• 930 points
815 views
0 votes
1 answer
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,440 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,076 views
0 votes
2 answers

Why do we use return statement in python?

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

answered Apr 4, 2019 in Python by anonymous
2,025 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,560 points
2,570 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP