Variable Scope and Lifetime in Python

In Python, the scope of a variable refers to the region of the program where the variable is accessible, while the lifetime of a variable is the duration for which the variable exists in memory. Understanding these concepts is essential for managing variable accessibility and memory usage in your programs.

Key Points on Variable Scope:

Example of Variable Scope:

Code Example

x = 10  # Global variable
        
        def my_function():
            y = 5  # Local variable
            print("Inside function:", y)
            print("Global variable inside function:", x)
        
        my_function()
        print("Global variable outside function:", x)
        # print(y)  # Uncommenting this line will raise a NameError

Output

Inside function: 5
Global variable inside function: 10
Global variable outside function: 10

Variable Lifetime:

Understanding variable scope and lifetime helps developers write cleaner code, avoid unintended behavior, and manage memory efficiently.