The Wayback Machine - https://web.archive.org/web/20241002141708/https://www.geeksforgeeks.org/python-del-to-delete-objects/
Open In App

Python del to delete objects

Last Updated : 12 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The del keyword in Python is primarily used to delete objects in Python. Since everything in Python represents an object in one way or another, The del keyword can also be used to delete a list, slice a list, delete dictionaries, remove key-value pairs from a dictionary, delete variables, etc.

Syntax: del object_name

Below are various examples that showcase various use cases of the del keyword:

Del Keyword for Deleting Objects

In the program below we will delete Sample_class using del Sample_class statement.

Python3




class Sample_class:
    some_variable = 20
        
    # method of the class
    def my_method(self):
        print("GeeksForGeeks")
            
# check if class exists
print(Sample_class)
    
# delete the class using del keyword
del Sample_class
    
# check if class exists
print(Sample_class)


Output:

class '__main__.Sample_class'
NameError:name 'Sample_class' is not defined

Del Keyword for Deleting Variables

In the program below we will delete a variable using del keyword.

Python3




my_variable1 = 20
my_variable2 = "GeeksForGeeks"
  
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)
  
# delete both the variables
del my_variable1
del my_variable2
  
# check if my_variable1 and my_variable2 exists
print(my_variable1)
print(my_variable2)


Output:

20
GeeksForGeeks
NameError: name 'my_variable1' is not defined

Del Keyword for Deleting List and List Slicing

In the program below we will delete a list and slice another list using del keyword.

Python3




my_list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
my_list2 =["Geeks", "For", "Geek"]
    
# check if my_list1 and my_list2 exists
print(my_list1)
print(my_list2)
    
# delete second element of my_list1
del my_list1[1]
    
# check if the second element in my_list1 is deleted
print(my_list1)
    
# slice my_list1 from index 3 to 5
del my_list1[3:5]
    
# check if the elements from index 3 to 5 in my_list1 is deleted
print(my_list1)
    
# delete my_list2
del my_list2
    
# check if my_list2 exists
print(my_list2)


Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
['Geeks', 'For', 'Geek']
[1, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 4, 7, 8, 9]

NameError: name 'my_list2' is not defined

Del Keyword for Deleting Dictionaries and Removing key-value Pairs

In the program below we will delete a dictionary and remove few key-value pairs using del keyword.

Python3




my_dict1 = {"small": "big", "black": "white", "up": "down"}
my_dict2 = {"dark": "light", "fat": "thin", "sky": "land"}
    
# check if my_dict1 and my_dict2 exists
print(my_dict1)
print(my_dict2)
    
# delete key-value pair with key "black" from my_dict1
del my_dict1["black"]
    
# check if the  key-value pair with key "black" from my_dict1 is deleted
print(my_dict1)
    
# delete my_dict2
del my_dict2
    
# check if my_dict2 exists
print(my_dict2)


Output:

{'small': 'big', 'black': 'white', 'up': 'down'}
{'dark': 'light', 'fat': 'thin', 'sky': 'land'}
{'small': 'big', 'up': 'down'}

NameError: name 'my_dict2' is not defined

Please refer delattr() and del() for more details.



Similar Reads

delattr() and del() in Python
In this article, we are going to see delattr() and del() functions in Python delattr() in Python The delattr() method is used to delete the named attribute from the object, with the prior permission of the object. Syntax: delattr(object, name): The function takes only two parameter: object: from which the name attribute is to be removed.name: of th
3 min read
What Is Difference Between Del, Remove and Pop on Python Lists?
In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index. del Keyword: The del keyword delete any variable, list of values from a list
3 min read
List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()…) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentio
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Python Tkinter | Moving objects using Canvas.move() method
The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x
2 min read
Python | Unit Test Objects Patching | Set-1
The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.). To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual
2 min read
Python | Unit Test Objects Patching | Set-2
MagicMock instances that are normally used as replacement values are meant to mimic callables and instances. They record information about usage and allow to make assertions as shown in the code given below - Code #6: from unittest.mock import MagicMock m = MagicMock(return_value = 10) print(m(1, 2, debug = True), "\n") m.assert_called_wi
2 min read
Python objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
2 min read
Print objects of a class in Python
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
2 min read
Python: Difference between Lock and Rlock objects
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other codes. For simplicity, you can assume that a thread is si
5 min read
Flattening JSON objects in Python
JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard module
3 min read
Session Objects - Python requests
Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.
2 min read
Built-in Objects in Python-builtins
This Python module provides direct access to all 'built-in' identifiers of Python. For example, builtins.open is the full name for the built-in function open(). This module is not normally accessed explicitly by most applications, but can be useful in modules that provide objects with the same name as a built-in value, but in which the built-in of
3 min read
Encoding and Decoding Custom Objects in Python-JSON
JSON as we know stands for JavaScript Object Notation. It is a lightweight data-interchange format and has become the most popular medium of exchanging data over the web. The reason behind its popularity is that it is both human-readable and easy for machines to parse and generate. Also, it's the most widely used format for the REST APIs. Note: For
5 min read
Detecting objects of similar color in Python using OpenCV
OpenCV is a library of programming functions mainly aimed at real-time computer vision. In this article, we will see how to get the objects of the same color in an image. We can select a color by slide bar which is created by the cv2 command cv2.createTrackbar. Libraries needed:OpenCV NumpyApproach: First of all, we need to read the image which is
3 min read
Addition and Subtraction on TimeDelta objects using Pandas - Python
TimeDelta module is used to represent the time in the pandas module and can be used in various ways. Performing operations like addition and subtraction are very important for every language but performing these tasks on dates and time can be very valuable. Operations on TimeDelta dataframe or series - 1) Addition - df['Result'] = df['TimeDelta1']
2 min read
Creating nested dataclass objects in Python
Dataclasses is an inbuilt Python module which contains decorators and functions for automatically adding special methods like __init__() and __repr__() to user-defined classes. Dataclass Object is an object built into the Dataclasses module. This function is used as a decorator to add special methods directly to a user-defined class. This decorator
3 min read
Access object within another objects in Python
Prerequisite: Basics of OOPs in Python In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects w
2 min read
How to retrieve source code from Python objects?
We are given a object and our task is to retrieve its source code, for this we have inspect module, dill module and dis module built-in standard libraries in Python programming. They provide several useful functions to track information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. get
2 min read
How to compare JSON objects regardless of order in Python?
JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON and generate results. JSON is being used primaril
2 min read
How to get the list of all initialized objects and function definitions alive in Python?
In this article, we are going to get the list of all initialized objects and function definitions that are alive in Python, so we are getting all those initialized objects details by using gc module we can get the details. GC stands for garbage collector which is issued to manage the objects in the memory, so from that module, we are using the get_
2 min read
Unexpected Size of Python Objects in Memory
In this article, we will discuss unexpected size of python objects in Memory. Python Objects include List, tuple, Dictionary, etc have different memory sizes and also each object will have a different memory address. Unexpected size means the memory size which we can not expect. But we can get the size by using getsizeof() function. This will retur
2 min read
Get index in the list of objects by attribute in Python
In this article, we'll look at how to find the index of an item in a list using an attribute in Python. We'll use the enumerate function to do this. The enumerate() function produces a counter that counts how many times a loop has been iterated. We don't need to import additional libraries to utilize the enumerate() function because it's built-in t
2 min read
Python Pandas - Check whether two Interval objects overlap
The panda's Interval.overlaps() method is used to Check whether Interval objects are overlapping. Two intervals, including closed ends, overlap if they share the same point. Intervals that share only an open endpoint do not intersect. Interval.overlaps() function: Syntax: Interval.overlaps() parameters: other : interval object. Check for an overlap
2 min read
Python Pandas - Check whether two Interval objects that share closed endpoints overlap
In this article, we will cover how to check whether two intervals with sharing endpoint overlap or not. For this, we use the Interval class from pandas and the overlaps() method for all the interval-related operations. Syntax: Interval.overlaps() parameters: other : interval object. Check for an overlap using this interval. Returns : bool . returns
2 min read
Sort a list of objects by multiple attributes in Python
In this article, we are going to learn how to sort a list by multiple attributes with Python. Introduction Python is a dynamically typed language that offers numerous data types, such as list, tuple, set, dictionary, etc. and sorting is the most commonly used operation on any data structures such as list in Python. To perform this we can use the so
7 min read
Byte Objects vs String in Python
In Python 2, both str and bytes are the same typeByte objects whereas in Python 3 Byte objects, defined in Python 3 are "sequence of bytes" and similar to "unicode" objects from Python 2. In this article, we will see the difference between byte objects and strings in Python and also will look at how we can convert byte string to normal string and v
3 min read
Searching a list of objects in Python
Searching for a single or group of objects can be done by iterating through a list. You might want to search a list of objects to find the object in the list of objects. It is very hard to look for objects manually, you can use the below-discussed method to search for objects in a list. You can also use conditions to filter objects from list of obj
3 min read