Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

del() vs del statement in python [duplicate]

>>> 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

like image 568
Srinivas Avatar asked Nov 15 '18 15:11

Srinivas


People also ask

What is del () in Python?

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.

Why is Del not a function Python?

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!

Should Del be used in Python?

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.

What is the use of Del statement in list explain with example?

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.


2 Answers

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.

like image 105
Netwave Avatar answered Sep 19 '22 22:09

Netwave


The parenthehis is not mandatory with keyword (like if or del), but can put some if you want.

it's exactly the same thing

like image 26
iElden Avatar answered Sep 18 '22 22:09

iElden