0

When creating a lambda to be used by another class I create one for each element in a list. This then gets called by other code, but the values used are only for the last value in the list.

I have a workaround but it's important to me to understand what's happening in the internals so I can avoid and write better Python going forward.

This code prints out '5' for each element in the array when I would expect it to print out the values 0 to 5. Why is it only using the last value?

markets = [0,1,2,3,4,5]

# Print outs 5, 5, 5, 5, 5
def not_working():
    listeners = {
        mkt: lambda bid, ask: f"{bid} {mkt}"
        for mkt in markets}
    return listeners


for key, listener in not_working().items():
    print(listener(None, None))

This code prints correctly, but I don't really get why.

markets = [0,1,2,3,4,5]

# Prints out 1 2 3 4 5
make_lambda = lambda mkt: lambda bid, ask: mkt
def working():
    listeners = {
        mkt: make_lambda(mkt)
        for mkt in markets}
    return listeners

for key, listener in working().items():
    print(listener(None, None))
Henry B
  • 7,795
  • 9
  • 41
  • 46
  • 1
    This question in the official FAQ: [Why do lambdas defined in a loop with different values all return the same result?](https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) – wim Sep 07 '21 at 15:50

0 Answers0