# Unexpected behaviour of lambda function?

**URL:** <https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633>\
**Category:** Python Help\
**Created:** [August 31, 2022, 2:46pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633 "2022-08-31T14:46:57Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Blackward](https://avatars.discourse-cdn.com/v4/letter/b/f08c70/32.png) [@Blackward](https://discuss.python.org/u/Blackward)\
**Post date:** [August 31, 2022, 2:46pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/1 "2022-08-31T14:46:57Z")

</div>

Howdy Folks,

I am a little baffled:

![2022-08-31_PythonFctList](https://us1.discourse-cdn.com/flex002/uploads/python1/original/2X/e/eda0df6964262b7cec99ed900b8ca7ba3a2fad47.png)

I would have expected an output of 0…9 - not 10 times 9… Can someone explain me why this happens - I do not get it?

Thanks and Cheers  
Dominik

---

<div class="post-metadata">

**Author:** ![Blackward](https://avatars.discourse-cdn.com/v4/letter/b/f08c70/32.png) [@Blackward](https://discuss.python.org/u/Blackward)\
**Post date:** [August 31, 2022, 3:05pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/2 "2022-08-31T15:05:25Z")

</div>

OK, I obviously had some minutes of dumbness - now I think, I can answer it for myself - ‘indexI’ is not ‘replaced’ by the integer 0…9 but instead refers to the object containing an integer - said 9 - after the loop. This is due to the fact, that the lambda expression is not evaluated at the time of definition, but at the time of execution - right? Any ideas for a nice solution getting 0…9?

---

<div class="post-metadata">

**Author:** ![zware](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/zware/32/58_2.png) [@zware](https://discuss.python.org/u/zware)\
**Post date:** [August 31, 2022, 3:17pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/3 "2022-08-31T15:17:46Z")

</div>

You’ve found your way into an issue common enough to be a [FAQ](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) 🙂

Note: in future, please post code directly using a preformatted text “code block” (see the `</>` button in the edit toolbar) rather than posting a screenshot of code.

---

<div class="post-metadata">

**Author:** ![Blackward](https://avatars.discourse-cdn.com/v4/letter/b/f08c70/32.png) [@Blackward](https://discuss.python.org/u/Blackward)\
**Post date:** [August 31, 2022, 3:17pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/4 "2022-08-31T15:17:47Z")

</div>

This seems to work

```auto
fctL = []
for indexI in range(10):
    fctL.append( eval("lambda x: %d" % indexI) )

for fct in fctL:
    print (fct(0))

```

---

<div class="post-metadata">

**Author:** ![Zeturic](https://avatars.discourse-cdn.com/v4/letter/z/ecb155/32.png) [@Zeturic](https://discuss.python.org/u/Zeturic)\
**Post date:** [August 31, 2022, 7:04pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/5 "2022-08-31T19:04:20Z")

</div>

A simple solution would be something like

```python
fctL = []
for indexI in range(10):
    fctL.append(lambda x=indexI: x)

for fct in fctL:
    print(fct())

```

By using `indexI` as the default value for your lambda, you’re capturing its value at the time of creating your lambda, rather than capturing a reference to the variable itself (which will be modified), as in the original.

---

<div class="post-metadata">

**Author:** ![Henkhogan](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/henkhogan/32/9913_2.png) [@Henkhogan](https://discuss.python.org/u/Henkhogan)\
**Post date:** [October 23, 2023, 8:36pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/6 "2023-10-23T20:36:16Z")

</div>

It seems like the same applies for locally defined functions, which is very similar to lambdas - but should be explicitly document as well.

Example:

```auto
def outer():

    fd = {}

    for _ in range(5):
    
        s = f"{_}"
        
        def inner():
            return s

        fd[_] = inner

    return fd

if __name__ == ' __main__':
    for k,v in outer().items():
        print(f'{v()} should be {k}')

```

Unfortunately this is really annoying when the inner() function is supposed to be a callback that is passed from the loop

---

<div class="post-metadata">

**Author:** ![Rosuav](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/rosuav/32/3429_2.png) [@Rosuav](https://discuss.python.org/u/Rosuav)\
**Post date:** [October 23, 2023, 10:27pm UTC](https://discuss.python.org/t/unexpected-behaviour-of-lambda-function/18633/7 "2023-10-23T22:27:05Z")

</div>

> [@Henkhogan](#):
>
> It seems like the same applies for locally defined functions, which is very similar to lambdas - but should be explicitly document as well.

Yes; the behaviour you’re seeing isn’t special to lambda, and in fact, there’s nothing special about lambda functions at all (at least, not in any technical sense). Whatever you can do with a lambda function, you can do with a def function, and the effect will be the same. The lambda keyword just gives you a convenient way of inlining a function definition in the place where it’s going to be used.
