Why did the creators of python prefer this syntax (instruction)
del list[index]
over this (method)?
list.del(index)
It seems to me that del
belongs to the same "cathegory" as append
, remove
, find
, e.t.c. and therefore should have the same syntax (be a method), but due to some reason the creators of python implemented it as an instruction. Why did they do it?
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.
When is del useful in python? You can use it to remove a single element of an array instead of the slice syntax x[i:i+1]=[] . This may be useful if for example you are in os. walk and wish to delete an element in the directory.
delattr() and del() in Python delattr(object, name): The function takes only two parameter: object: from which the name attribute is to be removed. name: of the attribute which is to be removed.
The del statement is used to delete a name from the scope of the program. When the del statement is used on a name, that name's identity is gone. Any subsequent references to it will throw a NameError exception.
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!
Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.
Deletion of a target list recursively deletes each target, from left to right.
Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.
Deletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).
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