The other answers are looking at it from a technical point of view (i.e. what's the best way to modify a list), but I would say the (much) more important reason people recommend, for example, slicing, is that it doesn't modify the original list.
The reason for this in turn is that usually, the list came from somewhere. If you modify it, you can unknowningly cause serious and hard-to-detect side effects, which can cause bugs elsewhere in the program. Or even if you don't cause a bug immediately, you'll make your program overall harder to understand and reason about, and debug.
For example, list comprehensions/generator expressions are nice in that they never mutate the "source" list they are passed:
[x for x in lst if x != "foo"] # creates a new list
(x for x in lst if x != "foo") # creates a lazy filtered stream
This is of course often more expensive (memory wise) because it creates a new list but a program that uses this approach is mathematically purer and easier to reason about. And with lazy lists (generators and generator expressions), even the memory overhead will disappear, and computations are only executed on demand; see http://www.dabeaz.com/generators/ for an awesome introduction. And you should not think too much about optimization when designing your program (see https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil). Also, removing an item from a list is quite expensive, unless it's a linked list (which Python's list
isn't; for linked list, see collections.deque
).
In fact, side-effect free functions and immutable data structures are the basis of Functional Programming, a very powerful programming paradigm.
However, under certain circumstances, it's OK to modify a data structure in place (even in FP, if the language allows it), such as when it's a locally created one, or copied from the function's input:
def sorted(lst):
ret = list(lst) # make a copy
# mutate ret
return ret
— this function appears to be a pure function from the outside because it doesn't modify its inputs (and also only depends on its arguments and nothing else (i.e. it has no (global) state), which is another requirement for something to be a Pure Function).
So as long as you know what you're doing, del
is by no means bad; but use any sort of data mutation with extreme care and only when you have to. Always start out with a possibly less efficient but more correct and mathematically elegant code.
...and learn Functional Programming :)
P.S. note that del
can also be used to delete local variables and thus eliminate references to objects in memory, which is often useful for whatever GC related purposes.
Answer to your second question:
As to the second part of your question about del
removing objects completely — that's not the case: in fact in Python, it is not even possible to tell the interpreter/VM to remove an object from memory because Python is a garbage collected language (like Java, C#, Ruby, Haskell etc) and it's the runtime that decides what to remove and when.
Instead, what del
does when called on a variable (as opposed to a dictionary key or list item) like this:
del a
is that it only removes the local (or global) variable and not what the variable points to (every variable in Python holds a pointer/reference to its contents not the content itself). In fact, since locals and globals are stored as a dictionary under the hood (see locals()
and globals()
), del a
is equivalent to:
del locals()['a']
or del globals()['a']
when applied to a global.
so if you have:
a = []
b = a
you're making a list, storing a reference to it in a
and then making another copy of that reference and storing it into b
without copying/touching the list object itself. Therefore, these two calls affect one and the same object:
a.append(1)
b.append(2)
# the list will be [1, 2]
whereas deleting b
is in no way related to touching what b
points to:
a = []
b = a
del b
# a is still untouched and points to a list
Also, even when you call del
on an object attribute (e.g. del self.a
), you're still actually modifying a dictionary self.__dict__
just like you are actually modifying locals()
/globals()
when you do del a
.
P.S. as Sven Marcnah has pointed out that del locals()['a']
does not actually delete the local variable a
when inside a function, which is correct. This is probably due to locals()
returning a copy of the actual locals. However, the answer is still generally valid.
del
is probably not bad, but the existence of the syntaxdel
for deleting list indices is an awkward feature of the language, just likelen(..)
, both of which annoy newcomers who complain about it going against the grain of other popular languages without a clear justification. – Cleanshavenlen
, why havelist.length
,str.length
,array.length
, etc., when you can have one function that gives you the length of any object that can reasonably have one? (i.e., any object with a__len__
)? – Lussilen
that someone mentioned ismap(len, listoflists)
, so it has its place. I don't see why we shouldn't have a.size()
method on built-in data structures too. The built-inlen(..)
does a bit of checking after calling an object's.__len__()
, but it seems to be more paranoid than useful #496509 – Cleanshavenlen
has been hanging around Python longer than that's been reasonably possible to implement. I guess that could have been done in Py3k but it's not like Python has a ridiculous number of global built-ins likelen
and needs to pare down. – Lussi.__len__()
shouldn't be magic. (It should be called.size()
andlen(x)
will callx.size()
or you can just usex.size()
.) – Cleanshavendel
andappend
. – Waring