Python: Deleting Variables and Garbage Collection

Python: Deleting Variables and Garbage Collection

When you create variables in Python, they live in memory as long as something in your program still refers to them. But once no one needs them anymore, Python will automatically clean them up — this process is called garbage collection.

In this lesson, we’ll learn how Python handles memory automatically and how you can manually delete variables when needed.

1. What Happens When You Create a Variable

When you create a variable, Python:

  1. Creates an object in memory (e.g., a number, string, or list).
  2. Creates a reference (a label) that points to that object.
  3. Keeps track of how many references are pointing to that object.

Example:

x = [1, 2, 3]
y = x
  • Both x and y point to the same list in memory.
  • Python knows there are two references to that list.

If you delete one reference:

del x

The list still exists, because y still points to it. Only when no references remain, Python can safely remove the object from memory.


2. Deleting Variables Manually with del

You can use the del statement to delete variables or specific elements inside lists or dictionaries.

Example 1:

Deleting a variable

name = "Alice"
print(name)

del name           # Deletes the variable from memory
# print(name)      # Error: name is not defined

After running del name, the variable name no longer exists in memory — Python removes it from the namespace.

Example 2:

When you want to just one item from a list or Deleting elements from a list.

fruits = ["apple", "banana", "cherry"]
del fruits[1]       # Removes "banana"

print(fruits)

Output:

['apple', 'cherry']

3. How Python Automatically Cleans Memory

Python has a built-in system called the garbage collector. It automatically looks for objects that are no longer being used and frees their memory so the system can reuse it.

You don’t have to manually manage memory. Python handles it for you

Example:

def make_data():
    data = [1, 2, 3]
    print("Created:", data)

make_data()
print("Function finished.")

4. Check Memory Cleanup with gc Module

You can interact with the garbage collector using Python’s gc module.

Let’s see how it works:

import gc

# Check if automatic garbage collection is enabled
print(gc.isenabled())

# Force garbage collection manually
gc.collect()

Python will scan for unused objects and free them up. Python runs garbage collection automatically.


5. Reference Counting Behind the Scenes

Python keeps a reference counter for each object — this is how it knows when to delete something. You can check an object’s reference count using the sys module:

import sys

x = [1, 2, 3]
print(sys.getrefcount(x))   # Shows how many references exist

Each time you create a new variable that points to the same object, the count increases.

Example:

y = x
print(sys.getrefcount(x))   # Count increases

When you delete a variable using del, the count decreases. If the count reaches zero, Python knows it’s safe to delete the object.

🧾 Key Takeaways
  • del statement - Used to delete variables or specific items
  • Garbage Collection - Automatic memory cleanup handled by Python
  • Reference Count - Tracks how many variables point to an object
  • gc module - Lets you inspect or trigger garbage collection manually

Try It Yourself

You can try this short example to watch garbage collection in action:

import gc

def create_list():
    numbers = [1, 2, 3]
    print("Created:", numbers)

create_list()

# Manually call garbage collector
collected = gc.collect()
print(f"Garbage collector freed {collected} objects.")

💬 You don’t usually need to manage garbage collection in Python — but understanding it helps you write more memory-efficient code and avoid leaks in complex applications.

Hope this tutorial helps! Read our other tutorials to learn more.