Python Forum

Full Version: Scoped variables.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm trying out the code below but need help in understanding why the
it's printing 3 3 3 rather than 1 2 3.

list_of_printers = []
for i in [1, 2, 3]:
    def printer():
        print(i)
    list_of_printers.append(printer)

for func in list_of_printers:
    func()
Thanks in advance for any help.
When appending printer to the list of printers it is only adding the function name, at this point i does not exist in the function.
When the func is called from the list of printers it gets the value from i which will be the last value from the loop