1
for x in range(6):
    for y in range(4):
        button = Button(command = lambda x=x, y=y:show_symbol(x,y),width 
        =4, height = 2)
        button.grid(column = x, row = y, padx = 10, pady =10) 
        buttons[x,y] = button 
        button_symbols[x,y] = symbols.pop()
root.mainloop()

The above code is for a matchmaker game I am working on. I understand everything in the nested FOR loops except for the lambda function.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Please format code correctly in your question. `lambda x=x` is probably the [the identity function](https://en.wikipedia.org/wiki/Identity_function). Read the wikipage on [λ-calculus](https://en.wikipedia.org/wiki/Lambda_calculus) and the one on [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming))s – Basile Starynkevitch Feb 08 '20 at 06:50
  • I think `x=x, y=y` is assigning the current values of the variables `x` and `y` to default values for the function so they can be used in `show_symbol(x,y)` – khelwood Feb 08 '20 at 06:52

1 Answers1

2

The x=x in the lambda function definition is to declare a parameter x with the value of x, resolved from the x in the current scope within the for loop, as the default value.

In other words, the code:

for x in range(6):
    for y in range(4):
        button = Button(command = lambda x=x, y=y:show_symbol(x,y),width 
        =4, height = 2)

can be rewritten in a more readable way as follows:

for x in range(6):
    for y in range(4):
        def command(a=x, b=y):
            return show_symbol(a, b)
        button = Button(command=command, width=4, height=2)
blhsing
  • 91,368
  • 6
  • 71
  • 106