×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python del Keyword

By IncludeHelp Last updated : December 07, 2024

Description and Usage

del is a keyword (case-sensitive) in python, it is used to delete an object (like class's object, variable, list, part of the list, etc).

Note: After deleting an object – if you try to use it, a "NameError" occurs.

Syntax

Syntax of del keyword:

del object_name

Sample Input/Output

Input:
num = -21

# deleting
del a

# trying to print  - an error will occur
print(num)

Output:
NameError: name 'num' is not defined

Example 1: Delete a variable

# python code to demonstrate example of 
# del keyword 

# Delete a variable 

# declare a variable & assign a value

a = 100

# printing the value 
print("a = ", a)

# deleting the variable
del a 

# Printing the value - NameError will be generated
print("a = ", a)

Output

a =  100
Traceback (most recent call last):
  File "/home/main.py", line 17, in <module>
    print("a = ", a)
NameError: name 'a' is not defined

Example 2: Delete a class's object

# python code to demonstrate example of 
# del keyword 

# Delete a class's object

# defining a class
class student:
    name = "Aman"
    age = 21

# main code
# declaring object to the student class
std = student()

# printing values
print("Name: ", std.name)
print("Age: ", std.age)

# deleting the object 
del std

# printing values - will generate NameError
print("Name: ", std.name)
print("Age: ", std.age)

Output

Name:  Aman
Age:  21
Traceback (most recent call last):
  File "/home/main.py", line 23, in <module>
    print("Name: ", std.name)
NameError: name 'std' is not defined

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.