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 in Python 23 views

## 1 answer to this question.

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 by Haseeb

## How do I obtain the index list in a NumPy Array of all the NaN values present using Python?

Hi, it is pretty simple, to be ...READ MORE

## 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

## How do you write a loop in python with conditional statements in python?

Lets say we have a problem statement ...READ MORE

+1 vote

## 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

+1 vote

## how can i count the items in a list?

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

## how do i use the enumerate function inside a list?

can you give an example using a ...READ MORE

## Lowercase in Python

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