Python Frequently Asked Questions, Release 3.9.5 Chapter 2. Programming FAQ 10 config.py: The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example: Note that this behaviour is not peculiar to lambdas, but applies to regular functions too. Here,$_{n=x}$ creates a new variable$_{n}$ local to the lambda and computed when the lambda is defined so that it has the same value that$_{x}$ had at that point in the loop. This means that the value of$_{n}$ will be$_{0}$in the first lambda,$_{1}$in the second,$_{2}$in the third, and so on. Therefore each lambda will now return the correct result: In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global$_{x}$: This happens because$_{x}$ is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of x is 4 , so all the functions now return 4**2 , i.e. 16 . You can also verify this by changing the value of x and see how the results of the lambdas change: This gives you a list that contains 5 lambdas that calculate x**2 . You might expect that, when called, they would return, respectively,$_{0}$ ,$_{1}$ ,$_{4}$ ,$_{9}$ , and$_{16}$ . However, when you actually try you will see that they all return$_{16}$ : Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.: 2.2.3 Why do lambdas defined in a loop with different values all return the same result? 2.2.4 How do I share global variables across modules? x =0 # Default value of the 'x' configuration setting mod.py: import config config.x =1 main.py: >>> squares[2]() 4 >>> squares[4]() 16 >>> squares =[] >>> for x in range(5): ... squares.append( lambda n=x: n**2) >>> x =8 >>> squares[2]() 64 >>> squares[2]() 16 >>> squares[4]() 16 >>> squares =[] >>> for x in range(5): ... squares.append( lambda : x**2)