0

Iam trying to learn lambda expressions and came across the below :

funcs = {
        idx: lambda: print(idx) for idx in range(4)
        }

funcs[0]()

did not understand what is meant by funcs[0] ? Why the index and 0 ?

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 1
    It means execute the function at key `0` of `funcs`. The variable `funcs` references a dictionary where the keys are integers, hence the `[0]`. – Dani Mesejo Jan 23 '19 at 18:13
  • 2
    That has nothing to do with lambda expressions. It's just accessing a dictionary. – TigerhawkT3 Jan 23 '19 at 18:16
  • @chepner: What? Why would it be a KeyError? – user2357112 Jan 23 '19 at 18:17
  • @user2357112 I misread the dictionary comprehension; ignore my (now-deleted) comment. – chepner Jan 23 '19 at 18:18
  • 1
    (It's probably not doing what the author intended, unless the author intended it as a demonstration of closure variable lookup rules, but it's not a KeyError.) – user2357112 Jan 23 '19 at 18:18
  • The example shows different things: 1) building a dictionary from a loop (which is common in python), 2) You can build a dictionary of anything, so you may find useful to build a dictionary of functions : `funcs[0]()` means call the function corresponding to key 0. 3) It shows some of the problems of lazy evaluation (which `lambda` does), when you based a function on a scope variable inside a loop. In this case, the `lambdas` will always print the last value of `idx` (3), even if `idx` does not exist in the global scope (you cannot access it or edit it outside the loop) – Tarifazo Jan 23 '19 at 18:35

1 Answers1

0

This is a cool example to show how binding and scope work with lambda functions. As Daniel said, funcs is a dictionary of functions with four elements in it (with keys 0,1,2 and 3). What is interesting is that you call the function at key 0, you expect the index (idx) that was used to create that key to then print out and you'll get 0. BUT I believe if you run this code, you actually print 3! WHAT!?!? So what is happening is that the lambda function is actually not binding the value of 0 when it stores the reference to the function. That means, when the loop finishes, the variable idx has 3 associated with it and therefore when you call the lambda function in position 0, it looks up the reference to the variable idx and finds the value 3 and then prints that out. Fun :)

That was referring more to your question title than to the test... The 0 is to access the function that has key 0 in the dictionary.

nick
  • 1,310
  • 8
  • 15