Python del Keyword

Python del is keyword in Python programming language. del is used to delete object in Python. Below we will study about del keyword.

Syntax of Python del

del object_name

 

  • object_name is that object which need to be deleted.
  • object_name could be String, list, tuple, set, dictionary, class object etc.

 

Let’s understand Python del by taking few examples:

Delete a variable

 

[code language=”python”]

Python del Example

age =10
print(“age is:”,age)

del age

print(“age is:”,age)

[/code]

 

age is: 10

print("age is:",age)

NameError: name 'age' is not defined
  • age is variable
  • when we print age value it is 10.
  • When we apply del keyword on age, its deleted and when we try to print the value of age again, it throws error that NameError: name 'age' is not defined.

Delete a String

 

[code language=”python”]

#Python del Example

name=”learn Python”;

print(“name is:”,name)

del name

print(“variable is:”,name)

[/code]

name is: learn Python
print("variable is:",name)

NameError: name 'name' is not defined

 

Python del with a list

del can be used to delete Python list.

[code language=”python”]

#Python list del Example

name =[“Chandler”,”Joey”,”Ross”]

print(type(name))
print(“name is:”,name)

del name

print(“variable is:”,name)

[/code]

 

<class 'list'>
name is: ['Chandler', 'Joey', 'Ross']
print("variable is:",name)

NameError: name 'name' is not defined

 

Python del with a tuple

Let’s see how we can use del keyword with Python tuple.

 

 

[code language=”python”]

#Python tuple del Example

name =(“Chandler”,”Joey”,”Ross”)

print(type(name))
print(“name is:”,name)

del name

print(“variable is:”,name)

[/code]

 

<class 'tuple'>
name is: ('Chandler', 'Joey', 'Ross')
print("variable is:",name)

NameError: name 'name' is not defined

 

del with set

 

[code language=”python”]

#Python set del Example

name ={“Chandler”,”Joey”,”Ross”}

print(type(name))
print(“name is:”,name)

del name

print(“variable is:”,name)

[/code]

 

<class 'set'>
name is: {'Chandler', 'Joey', 'Ross'}
print("variable is:",name)

NameError: name 'name' is not defined

 

delete a dictionary

[code language=”python”]

#del with Python dictionary Example

dict1 ={“0″:”zero”,
“1”:”one”,
“2”:”two”}

print(type(dict1))
print(“name is:”,dict1)

del dict1

print(“dict is:”,dict1)

[/code]

 

 

<class 'dict'>
name is: {'0': 'zero', '1': 'one', '2': 'two'}

NameError: name 'dict1' is not defined

 

delete a function

 

[code language=”python”]

#del with Python function Example

def test() :
return “hi”

print(test())

del test

print(test())

[/code]

 

hi
NameError: name 'test' is not defined

 

del with class object

 

[code language=”python”]

#del with Python class Example

class Test :

def name(name) :
return name

print(Test.name(“hello”))

del Test

print(Test.name(“hello”))

[/code]

 

hello

NameError: name 'Test' is not defined

 

 

Scroll to Top