How to delete or clear variable from memory in Python - CodeSpeedy (2023)

Note: The del method can be used not just with variables but with all Python objects like arrays, lists, dictionaries etc.

In this case, the program returns a NameError exception. This is because the variable you are trying to access no longer exists in the variable namespace.

However, the above del method only removes the variable from the namespace. It does not remove the variable from the memory space.

The del method does not clear the variable from the memory. Hence, to clear the variable from memory you can resort to the gc.collect() method.
The gc.collect() method forces an immediate garbage collection of all generations. You can invoke the garbage collector as demonstrated below.

NameError Traceback (most recent call last)<ipython-input-21-a03cb7133a13> in <module> 4 del(a) 5 gc.collect()----> 6 print(a)NameError: name 'a' is not defined

In this case, you are deleting a from the memory space itself.

Just like the del method, you can invoke the gc.collect() for clearing the memory of not just variables but for all Python objects.

Example 2: Deleting a dictionary

import gca={1:10,2:9,3:8}print(a)del(a)gc.collect()print(a)
{1: 10, 2: 9, 3: 8}
---------------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-6-bde58578f7de> in <module> 4 del(a) 5 gc.collect()----> 6 print(a)NameError: name 'a' is not defined

Thus, you can use a combination of del() and gc.collect() to clear the variable from Python memory.

On a side note, though not very relevant, you can use the dir() method to get a list of the names of all the objects in the current scope.

a = 5print(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i7', '_ii', '_iii', 'a']
a = 5print(dir())del aprint(dir())
['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii', 'a']['__', '___', '__builtin__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', '_i', '_i10', '_i9', '_ii', '_iii']

In order to understand more about garbage collection in general, do refer to https://docs.microsoft.com/en-us/dotnet/api/system.gc.collect?view=net-6.0

Also read:Python Variable Scope And Lifetime

FAQs

How do you clear a variable from memory in Python? ›

The "del" statement is used to delete variables or objects in Python. It is a powerful feature that allows you to remove variables, lists, dictionaries, and other objects from memory. This article will explain what the "del" function is, its syntax, return value, and provide examples of how to use it.

How do I clear a variable in memory? ›

How to Delete Variables & Objects from Memory
  1. Method 1: Delete Variable using del or None from Memory.
  2. Method 2: Delete List or Dictionary using del or None from Memory.
  3. Method 3: Delete a Function using del or None from Memory.
  4. Method 4: Delete User Defined Objects with dir() and globals()
  5. Method 5: Use the gc library.
28 Aug 2022

How do I fix memory problems in Python? ›

Ways to Handle Python Memory Error and Large Data Files
  1. Allocate More Memory.
  2. Work with a Smaller Sample.
  3. Use a Computer with More Memory.
  4. Use a Relational Database.
  5. Use a Big Data Platform.
18 Apr 2022

How do I resolve memory problems in Python? ›

Avoiding Memory Errors in Python

We can solve such issues by running Generator functions. It may be implemented as a user-defined method when dealing with large datasets. Without importing the entire dataset, we can easily divide big datasets into several pieces thanks to Python generator functions.

What does Del () do in Python? ›

The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.

Can you delete a variable? ›

The Remove-Variable cmdlet deletes a variable and its value from the scope in which it is defined, such as the current session. You cannot use this cmdlet to delete variables that are set as constants or those that are owned by the system.

How do you set a variable to nothing in Python? ›

Defining empty variables in Python is straightforward. If you wish to define a placeholder for a missing value that will not be used for calculations, you can define an empty variable using the None keyword. This is useful because it clearly indicates that the value for a variable is missing or not valid.

Which command removes a variable from memory? ›

Using the 'del' command is the most known and easiest method to delete variables in Python.

How to clear variable memory in C? ›

You cannot delete a variable in C, nor in C++. A variable disappears when it goes out of scope. Perhaps you mean that you have a pointer variable, and it is currently pointing to a memory address you got back from a call to something like malloc().

How to clear variable memory in R? ›

We use rm() function to remove variables while the arguement "list = ls()" will make sure all of the variables are removed from the list. ls() gives the list of all the variables in the session. This would also remove functions assigned in the session.

How do you clear variables in command prompt? ›

However, you can clear the value of an environment variable using Command Prompt. To unset an environment variable from Command Prompt, type the command setx variable_name “”. For example, we typed setx TEST “” and this environment variable now had an empty value.

References

Top Articles
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated: 28/12/2023

Views: 6470

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.