Nearby lessons
52 of 159Python - del and None
- Define the del keyword and the None value
- Delete variables with the del keyword
- Understand the NameError raised when accessing a deleted variable
- Explain why deleting an element of a string raises a TypeError
- Distinguish the unbind operation of del from the rebind operation of assigning None
Introduction
Python provides the del keyword to delete variables.
Python also provides the special value None, which represents "no value".
Although both are related to object management, they work differently.
del Statement
del is a keyword in Python.
After using a variable, it is recommended to delete it if it is no longer required.
After deleting the variable, the corresponding object becomes eligible for Garbage Collection (if no other references exist).
Syntax
Example 1 - Delete a Variable
Example 2 - Accessing a Deleted Variable
After deleting a variable, it cannot be accessed.
If we try to access it, Python raises a NameError.
Program
Important Note
We can delete variables that point to immutable objects.
However, we cannot delete individual elements of an immutable object.
Example - Immutable Object
Why Does This Error Occur?
A string is an immutable object.
Immutable objects cannot be modified after creation.
Therefore, deleting an individual character from a string is not allowed.
Difference Between del and None
Both del and None are used while working with variables, but their behavior is different.
Case 1 - Using del
- The variable is removed.
- The variable cannot be accessed afterwards.
- It is called an Unbind Operation.
Example - Using del
Case 2 - Assigning None
- The variable is not removed.
- The previous object becomes eligible for Garbage Collection (if no other references exist).
- The variable still exists.
- It is called a Rebind Operation.
Example - Assign None
Explanation
After assigning None, the variable still exists.
Its value becomes None.
Therefore, it can still be accessed.
Comparison Between del and None
| del | None |
|---|---|
| Removes the variable. | Does not remove the variable. |
| Variable cannot be accessed. | Variable can still be accessed. |
| Unbind operation. | Rebind operation. |
Raises NameError when accessed. |
Prints None. |
| Object becomes eligible for Garbage Collection. | Previous object becomes eligible for Garbage Collection. |
Real World Usage
The del keyword and None are commonly used in:
- Memory management
- Large applications
- Object cleanup
- Resetting variable values
- Garbage collection optimization
- del is a Python keyword used to delete variables
- Accessing a deleted variable raises a NameError
- Individual elements of immutable objects like strings cannot be deleted
- Deleting a variable is called an unbind operation
- Assigning None is called a rebind operation and the variable still exists