Date: January 1st 2016
Last updated: January 19th 2016

Surprisingly, del does not delete variables. According to Python in a Nutshell by Alex Martelli (page 49), del simply unbinds references. I must admit that deleting variables has not been something I have paid close attention to.


var_a = 'test' # assign a string
var_b = 2 # assign a number 

print 'var_a = %s, var_b = %s' %(var_a, var_b) 
# py34 requires parentheses

# "delete" one variable
del var_a

# run
except NameError:  
    print 'var_a does not exist'

# Output  
#var_a = test, var_b = 2  
#var_a does not exist

del is useful in string splicing:

test = list('vowels') # ['v','o','w','e','l','s']
del test[1:4:2] # [start: stop: stride]
# unbind 'o' and 'e' 
# start with 'o' at index 1
# stop at 'l' at index 4
# step by two, unbinding indices 1 and 3

# output
# ['v', 'w', 'l', 's']

Another way of removing vowels in a string:

# loop through each letter
for i in range(1, len(test)-1):
    # if the letter is a vowel, delete it
    if test[i] in list('aeiou'):
        del test[i]

# output
# ['v', 'w', 'l', 's']

Notes on garbage collection

Note that Python has garbage collection and reference counting procedures for memory clean up ( Also if a variable is out of scope it will be cleaned up. In the code below, both x and y are not available as global variables because they are inside a function.

# test local scope

def my_variables():
    x, y = 1, 2
    return x + y

# Use %whos in Ipython to check variables 
# (

x, y

# Output (redacted)  
# NameError: name 'x' is not defined

results matching ""

    No results matching ""