>>> li = [1, 2, 3, 4]
>>> li
[1, 2, 3, 4]
>>> del li[2] #case 1
>>> li
[1, 2, 4]
>>> del(li[2]) # case 2
>>> li
[1, 2]
>>> del (li[1]) # case 3
>>> li
[1]
>>>
One of my professors used case 2 to delete item from list.
As per python documentation case 1 is right and there is also another syntactic way exist from this answer so case 3 also right, but as per my knowledge there is no del method exist in python, how case 2 is valid. I searched whole python documentation but could not find it.
Update: if i write del method myself in my module and use case 2 at same time, how python interpreter differentiates between them or will it through an error, although i never tried until now
Definition and Usage. The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.
Because del is a statement that you can delete several things with it, and since when you want to delete list_name[index] with del actually you want to delete an object and this is the job that del does for other objects so there is no need to create an redundant attribute for lists to does that!
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.
Python's del statement is used to delete variables and objects in the Python program. Iterable objects such as user-defined objects, lists, set, tuple, dictionary, variables defined by the user, etc. can be deleted from existence and from the memory locations in Python using the del statement.
All of them are the same, del
is a keyword as yield
or return
, and (list[1])
evaluates to list[1]
. So del(list[1])
and del (list[1])
are the same. For the base case, since you dont have the ()
you need to force the extra space, hence del list[1]
.
EDIT: You cannot redifine del
since it is a language keyword.
The parenthehis is not mandatory with keyword (like if
or del
), but can put some if you want.
it's exactly the same thing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With