Python del statement
- Del is a keyword in python.
Del statement in python: Del makes the object eligible for garbage collection.
What is garbage collection? : Garbage collection is a program which manages memory automatically.
- If you want to delete object or variable permanent by making the variable available for garbage collection using the del keyword.
- How to use del statement?
Delete object using delete keywordpython del statement Syntax
X = 10
If you don’t want X, delete X.
After deleting X using del, there is no chance to access the X variable.
Try to use X as
print(X) => Error
Accessing a deleted variable gives an error.
- String object does not support object deletion.
S = “python”
- You can delete multiple variables at a time.
X = 10
Y = 20
Del X, Y
Difference between del and none
- Del is to delete the object and none associated for none or no value.
- Suppose example you have two variable
S1 and S2
S1 = 10
S2 = 20
Then two objects are get created for S1 and S2
Now, assume you don’t require S1 variable and it’s the object in such case you can use del statement.
Both the variable and the object is deleted.
- But, In some cases you don’t require object but require variable for which you want to create another object, then you go for None.
S2 = None
Which deletes object not variable
After None statement S2 not pointing to any object.
See python none type
Python del statement and None example
print("python Del Statement")
X = 10
Y = 20
Y = None
- Consider another situation
Multiple variables are pointing to the same object what happens when we try to delete one variable using del statement?
Whenever we try to delete one variable that variable gets deleted but not the object as it is pointed by another object.
In our case, if we try to delete S1 then S1 get deleted but S2 and s3 still pointing to object.
del statement Program
S1 = 'python'
S2 = 'python'
S3 = 'python'
print ("s1=" ,id(S1))
print ("s2=" ,id(S2))
print ("s3=" ,id(S3))