3 Easy Ways to Delete a Variable in Python [with Examples] - JSON Viewer

3 Easy Ways to Delete a Variable in Python [with Examples]

What is a Variable in Python and Different types of Variables?

In Python, a variable is a container that can store different types of data, such as numbers, text, or lists of values. It is dynamically typed so there is no need to tell Python what type of value a variable will hold; it figures it out automatically based on what you assign to it.

For creating a variable, you simply assign a value to a name using the assignment operator =.

For example:

x = 10
y = "Goom"
z = [1,2,3,4,5]

From the example shown, x, y and z are the variables having some values. The variable x has an integer value 10, variable y has a string value “Goom” and variable z has a list of numbers.

You can also assign the value of one variable to another variable. For example:

x = 12
y = x

In this example, y is a variable that refers to the same integer value as x.

Python has two main types of variable i.e, Local variable and Global variable.

We can see what is a local variable and global variable.

Local variable

In Python, a local variable is a variable that is defined inside a function and can only be accessed within that function only. It is not accessible outside the function in which they are defined.

We can see one example,

def my_function():
    num = 10
    print(num)
my_function()

In this example, num is the local variable that has an integer value 10 and it is defined inside the my_function.

We can go with other example,

def my_function():
    x = 5
    print(x)
my_function()
def my_num():
   x = 5
   print(x)
my_num()
def my_value():
    x = 4
    print(x)
my_value()
def my_number():
    x = 4
    print(x)

In this example we have four functions, each of which declares a local variable x within its own scope. However, the value assigned to x in the third and fourth functions is different from the other two functions.

When my_function is called, it declares a local variable x and assigns it the value 5, and then prints the value of x.

Similarly, when my_num is called, it declares a local variable x and assigns it the value 5, and then prints the value of x.

However, when my_value is called, it declares a local variable x and assigns it the value 4, and then prints the value of x.

Likewise, when my_number is called, it also declares a local variable x and assigns it the value 4, and then prints the value of x.

The key point to understand here is that local variables are only accessible within the function where they are declared.

So, even though all four functions have a local variable named x, each x variable is a separate and distinct variable that is only accessible within the corresponding function. Therefore, changing the value of x in one function does not affect the value of x in any of the other functions.

Global variable

Global variable in python is defined outside the function. So, it can be accessed from anywhere in the program.

For example,

num = 10
def my_function():
    print(num)
my_function()

Here num is the global variable having an integer value 10 and it is defined outside the my_function. It can be accessed from anywhere.

We can see one more example,

x = 5
def my_function():
    print(x)
my_function()
def my_num():
    print(x)
my_num()
def my_value():
    print(x)
my_value()
def my_number():
    print(x)
my_number()

In this example, x is declared and assigned the value 5 outside of any function, which makes it a global variable.

The first function my_function simply prints the value of x, which is 5, when it is called. Since x is a global variable, it can be accessed and printed from within any function.

The second function my_num also prints the value of x when it is called, and since x is a global variable, it will still print 5.

The third function my_value also prints the value of x, which is still 5.

The fourth function my_number also prints the value of x, which is again 5.

Overall, this example demonstrates how a global variable can be accessed and used within multiple functions.

Memory Management in Python

In Python, when you create an object, it takes up memory on your computer. The Python interpreter keeps track of how many times that object is being used, and when no one is using it anymore, the interpreter frees up the memory so your computer can use it for something else.

This process is called “garbage collection” and it happens automatically in Python. You don’t need to worry about it too much, but you can use a special module called “gc” to control it if you need to.

Why Should one Delete Variables?

Deleting variables in Python can be useful in certain situations, such as managing memory usage and preventing errors caused by name clashes.

Some reasons why you might want to delete variables include freeing up memory, avoiding name clashes, improving security, ensuring reusability, reducing bugs, improving readability, resetting state, and improving performance.

Freeing memory: When a large set of data or a program is using a lot of memory then we can delete the variables that are no longer needed to free up memory.

Performance increase: Deleting variables reduces the memory of the code and this can improve the performance.

security: To prevent unauthorised access to sensitive data, such as passwords or other confidential information, it can be helpful to delete that data from memory.

Reduce bugs: If you accidentally reuse a variable in a way that causes unexpected behaviour, deleting the variable can help prevent these types of bugs by ensuring that the variable is not reused unintentionally.

Different Ways to Delete a Variable in Python

Using the del Keyword

1.Deleting one variable: we can use the ‘del’ keyword to delete one variable.

Let’s move with an example,

my_num = 10
del my_num

By using ‘del’ it will remove the variable ‘my_num’ from memory.

2.deleting multiple variables

Not only one variable we can remove multiple variables using del. Let’s see one example

x = 10
y = 20
del x, y

In this example it is deleting multiple variables in one statement by separating their names with commas. So, it will remove both the x and y.

3.deleting a variable from a list

my_list = [1, 2, 3, 4, 5]
del my_list[3]
print(my_list)
# output = [1, 2, 4, 5]

From this example using the del keyword it deletes the fourth element (with index 3) from my_list.

4. deleting variables from a dictionary

my_dict = {"name": "Alan", "age": 25, "designation": "Engineer","id":2,"height":170}
# delete a single key-value pair
del my_dict["age"]
# delete multiple key-value pairs
del my_dict["name"], my_dict["designation"]
print(my_dict)
#output = {'id': 2, 'height': 170}

By using del keyword we can remove both single key-value pair and multiple key-value pair. It is shown in this example First it is taking the key “age” from my_dict then it will delete the value of age i.e, 25. Next it is deleting multiple key-value pairs i.e the name and the designation.

5.deleting variable from a loop

my_num = [2, 3, 4]
for i in my_num:
x = i * 2
print(x)
del x

This will print the numbers 4, 6 and 8 then delete the variable x after each iteration.

Using dir() and global()

In Python, you can also delete variables using the dir() and global() functions together. This method is particularly useful when you want to delete multiple variables at once.

dir() returns a list of all the currently defined symbols in the current scope. We can use a loop to iterate over this list and check whether each symbol is a variable that we want to delete.

Then, we use global() to get a reference to the global variable with that name, and delete it using the del keyword.

Here is an example of dir() and global()

# print the values of x, y, and z
print(x)  # prints 5
print(y)  # prints 10
print(z)  # prints "hello"
# delete the variables x and y using dir() and global()
for var_name in dir():
   if not var_name.startswith("__") and var_name in ["x", "y"]:
       global_var = globals()[var_name]
       del global_var
# try to print the values of x and y (raises NameError)
print(x)
print(y)
# print the value of z
print(z)  # prints "hello"

In this example, we can see three variables x, y, and z, and then print their values. We then use a loop with dir() to check for the existence of the variables x and y, and then use global() to get a reference to those variables, which are then deleted using the del keyword.

After the deleting x and y, we attempt to print their values again, which raises a NameError since the variables no longer exist. Finally, we print the value of z to confirm that it was not affected by the deletion.

Let’s see another example

x = 5
y = "hello"
z = [1, 2, 3]
# print the values of x, y, and z
print(x)  # prints 5
print(y)  # prints "hello"
print(z)  # prints [1, 2, 3]
# delete the variables x and y using dir() and global()
for var_name in dir():
   if not var_name.startswith("__") and var_name in ["x", "y"]:
       global_var = globals()[var_name]
       del global_var
# try to print the values of x and y (raises NameError)
print(x)
print(y)
# try to print the value of z (still exists)

In this example, we define three variables x, y, and z, and then print their values. We then use a loop with dir() to check for the existence of the variables x and y, and then use global() to get a reference to those variables, which are then deleted using the del keyword.

After the deletion of x and y, we attempt to print their values again, which raises a NameError since the variables no longer exist. Finally, we try to print the value of z, which still exists since it was not included in the list of variables to delete.