Is the use of del bad?

2019-01-22 01:31发布

I commonly use del in my code to delete objects:

>>> array = [4, 6, 7, 'hello', 8]
>>> del(array[array.index('hello')])
>>> array
[4, 6, 7, 8]
>>> 

But I have heard many people say that the use of del is unpythonic. Is using del bad practice?

>>> array = [4, 6, 7, 'hello', 8]
>>> array[array.index('hello'):array.index('hello')+1] = ''
>>> array
[4, 6, 7, 8]
>>> 

If not, why are there many ways to accomplish the same thing in python? Is one better than the others?

Option 1: using del

>>> arr = [5, 7, 2, 3]
>>> del(arr[1])
>>> arr
[5, 2, 3]
>>> 

Option 2: using list.remove()

>>> arr = [5, 7, 2, 3]
>>> arr.remove(7)
>>> arr
[5, 2, 3]
>>> 

Option 3: using list.pop()

>>> arr = [5, 7, 2, 3]
>>> arr.pop(1)
7
>>> arr
[5, 2, 3]
>>> 

Option 4: using slicing

>>> arr = [5, 7, 2, 3]
>>> arr[1:2] = ''
>>> arr
[5, 2, 3]
>>> 

I am sorry if this question appears to be opinion-based, but I am looking for a reasonable answer to my question, and I will add a bounty after 2 days if I don't get a suitable answer.

Edit:

Since there are many alternates to using del to delete certain parts of objects, the one unique factor left of del is its ability to remove objects completely:

>>> a = 'hello'
>>> b = a
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
'hello'
>>> 

However, what is the point of using it to 'undefine' objects?

Also, why does the following code change both variables:

>>> a = []
>>> b = a
>>> a.append(9)
>>> a
[9]
>>> b
[9]
>>> 

But the del statement does not achieve the same effect?

>>> a = []
>>> b = a
>>> del(a)
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> b
[]
>>> 

7条回答
对你真心纯属浪费
2楼-- · 2019-01-22 02:01

Nope, I don't think using del is bad at all. In fact, there are situations where it's essentially the only reasonable option, like removing elements from a dictionary:

k = {'foo': 1, 'bar': 2}
del k['foo']

Maybe the problem is that beginners do not fully understand how variables work in Python, so the use (or misuse) of del can be unfamiliar.

查看更多
登录 后发表回答