Inspired by this question.
Why is there no list.clear() method in python? I\'ve found several questions here that say the correct way to do it is one of the followin
I can't answer to the why; but there absolutely should be one, so different types of objects can be cleared with the same interface.
An obvious, simple example:
def process_and_clear_requests(reqs):
for r in reqs:
do_req(r)
reqs.clear()
This only requires that the object support iteration, and that it support clear(). If lists had a clear() method, this could accept a list or set equally. Instead, since sets and lists have a different API for deleting their contents, that doesn't work; you end up with an unnecessarily ugly hack, like:
def process_and_clear_requests(reqs):
for r in reqs:
do_req(r)
if getattr(reqs, "clear"):
reqs.clear()
else:
del reqs[:]
As far as I'm concerned, using del obj[:] or obj[:] = [] are just unpleasant, unintuitive hacks to work around the fact that list is missing clear().
This is taking "reducing redundancy" to a fault, where it damages the consistency of the language, which is even more important.
As to which you should use, I'd recommend del obj[:]. I think it's easier to implement for non-list-like objects.