What is del method in python?
The Python Show
Here, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc. Example 1: Delete an user-defined object
In the program, we have deleted MyClass using del MyClass statement. Example 2: Delete variable, list, and dictionary
Example 3: Remove items, slices from a listThe
Example 4: Remove a key:value pair from a dictionary
del With Tuples and StringsNote: You can't delete items of tuples and strings in Python. It's because tuples and strings are immutables; objects that can't be changed after their creation.
However, you can delete an entire tuple or string. The Syntax: del object_name Below are various examples that show-case various use-cases of the 1. del keyword for deleting objects Example:
Output: class '__main__.Sample_class' NameError:name 'Sample_class' is not defined 1. del keyword for deleting variables Example:
Output: 20 GeeksForGeeks 20 NameError: name 'my_variable2' is not defined 1. del keyword for deleting list and list slicing Example:
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 1. del keyword for deleting dictionaries and removing key-value pairs Example:
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. What is Del method?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 a dictionaries, remove key-value pairs from a dictionary, delete variables, etc. Syntax: del object_name.
What is the use of Del statement?The del statement can be used to delete an item at a given index. It can also be used to remove slices from a list.
How does Del work in Python list?Python del operator:
The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned, as it is with the pop() method. So essentially, this operator takes the item's index to be removed as the argument and deletes the item at that index.
How do you use Del?The preposition de is translated as "of," "from," or "about," but de also can mean "by," "in," or other prepositions in some cases. Del is simply the contraction of de and the definite article el (not él), so we use del in place of de el.
|