Why use del() instead of pop()?


#1

array.pop(x) and del(array[x]) serve the same purpose, but del doesn’t return anything. Is a function returning something but doing something else wasteful, bad form, or is there another reason to use del vs pop?


#2

pop() is useful if we wish to discard values beforethey have been processed, rather than after.

temp = array.pop()

array is now one element shorter but the temp value is still in play. This as opposed to,

temp = array[-1]
del(array[-1])

del() goes much further, though. We del objects completely with this function.

del(array)
print array    # NameError: name 'array' is not defined

Above we can see that pop() lets us write one statement, instead of two, and uses no indexing. If the purpose is to remove the last element, then it just seems more appropriate to use the explicit function and not reach for the destructive one needing index references. Just a thought.


#3

del isn’t a function, and it doesn’t delete objects. It deletes names, or tells objects to delete an attribute or a value by key


#4

Objects that wish to support deletion of keys or attributes can implement what del ends up using. This is similar to looking up by key, or looping.

List likely has a pop method because of the lack of return value of del, but it is an operation that list wants to support

In cases where they overlap, you can’t really pick a wrong one since they’d be doing the same things. The extra work pop does is not significant, no.

Deleting is a fairly uncommon operation, typically you simply stop referring to something


#5

or slices, as viewed above. So it rermoves references to objects, then?


#6

No, references aren’t directly accessible. We get names and lists/dicts and anything else that’s supplied from some C module since those have direct memory access. Storage is magical in the sense that it can’t be defined by pure python
slices falls under key, since that’s done by sending a slice object as the key

>>> 'hello'[slice(1,3)]
'el'

Well yeah, names store references… Delete a name and the reference goes with it, it’s just not something del did…And there might not even be a backing object


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.