Variable Lifetime and Garbage Collection in Python

Variable Lifetime and Garbage Collection in Python

Lesson 15. Variable Lifetime and Garbage Collection in Python

In Python, variable lifetime refers to how long a variable exists in memory, while garbage collection is the process that automatically removes unused variables to free up memory.

Let’s break this down step by step:

  1. What Is Variable Lifetime?

Every variable in Python has a lifetime — the period between its creation and its deletion from memory.

Think of it like this:

When you create a variable, Python reserves a space in memory for it. When you no longer need it (or it goes out of scope), Python automatically cleans it up.

🔹 Local Variable Lifetime

Local variables are created when a function starts and destroyed when the function ends.

def greet():
    message = "Hello"  # Created when function runs
    print(message)

greet()
# message no longer exists after this point

Explanation:

  • message is created inside the greet() function
  • When the function finishes, Python automatically deletes it.
  • You can’t access it afterward — it’s deleted from memory.

2️⃣ Global Variable Lifetime

Global variables live as long as your program runs. They’re created when Python first reads your code and deleted when the program ends.

name = "Alice"  # Created at program start

def show_name():
    print(name)

show_name()  # Output: Alice
# 'name' still exists until the entire program finishes
  1. **Python’s Memory Management</b>**

Python automatically handles memory using a system called reference counting and garbage collection.

Each object in Python keeps track of how many variables refer to it (called references).

a = [1, 2, 3]   # One reference
b = a            # Now two references point to the same list

del a            # Removes one reference
print(b)         # Still works because 'b' still refers to it

🧩 Explanation:

  • The list [1, 2, 3] stays in memory as long as at least one variable refers to it.
  • Once no variables point to it, Python automatically removes it.

Garbage Collection

When objects are no longer needed (i.e., no references point to them), Python’s garbage collector automatically deletes them to free up memory.

You normally don’t have to do anything — Python handles this in the background.

import gc

# Manually trigger garbage collection (optional)
gc.collect()

💡 Note: You almost never need to call gc.collect() yourself. Python does it efficiently whenever necessary.

3. Reference Cycles (and How Python Handles Them)

Sometimes, two objects might reference each other — creating a reference cycle that could prevent automatic cleanup. Python’s garbage collector is smart enough to detect and remove these cycles.

class Node:
    def __init__(self):
        self.ref = None

a = Node()
b = Node()

a.ref = b
b.ref = a

Explanation:

  • a and b refer to each other, creating a cycle.
  • Even if both are deleted, Python’s garbage collector will eventually clean them up.

Try It Yourself

Let’s test a variable lifetime:

def demo():
    x = 100
    print("Inside function:", x)

demo()
# Try printing x here
# print(x)  # ❌ NameError: x is not defined

Observation:

  • x exists only while the function runs.
  • Once the function ends, x is destroyed — freeing up memory.

Key Takeaways

  • Every variable has a lifetime — from creation to deletion.
  • Python automatically manages memory using reference counting and garbage collection.
  • You rarely need to free memory manually — Python does it for you.

Mini Challenge Try this:

def test_scope():
    temp = "I'm temporary!"
    print(temp)

test_scope()
print(temp)  # What happens here?

Question: Did you get an error?. Why does this cause an error?

Think in terms of scope and lifetime — and you’ll understand Python’s memory magic better.

Happy coding!!