Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no list.clear() method in python?

Tags:

python

list

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 following, but no one has said why there isn't just a method for it.

del lst[:] lst[:] = [] 

While it may go against the "zen of python" to have more than one way of doing something, it certainly seems more obvious to me to have a "list.clear()" method. It would also fall in line with dicts and sets, both of which have .clear().

I came across a few posts to the python-dev and python-ideas concerning this and didn't come to a definitive answer (see here (2006) and here (2009)). Has Guido weighed in on it? Is it just a point of contention that hasn't been resolved yet over the last 4-5 years?

Update: list.clear() was added to python in 3.3 - see here

like image 504
job Avatar asked Sep 09 '09 20:09

job


People also ask

How do you make a list clear in Python?

Using del() The del() function you can selectively remove items at a given index or you can also remove all the elements, making the list empty. In the below example we take a list, remove the element at index 2. Then we remove all the elements.

What does list Clear () do Python?

The clear() method removes all the elements from a list.

Is there a clear function in Python?

If you are a Windows user and want to clear the screen in Python, you can easily do it using the "cls" command.

What is the difference between delete () and clear () method of lists?

del can delete specific elements from the list or the complete list. It can delete a specific value from the list. pop() can delete specific values from the list using its index. The clear() method can delete all the elements from the list, making the list empty.


1 Answers

In the threads you linked Raymond Hettinger pretty much sums up the pros and cons of adding that method. When it comes to language design, it's really important to be conservative. See for example the "every feature starts with -100 points" principle the C# team has. You don't get something as clean as Python by adding features willy-nilly. Just take a look at some of the more cruftier popular scripting languages to see where it takes you.

I guess the .clear() method just never did cross the implicit -100 points rule to become something worth adding to the core language. Although given that the methodname is already used for an equivalent purpose and the alternative can be hard to find, it probably isn't all that far from it.

like image 169
Ants Aasma Avatar answered Oct 08 '22 21:10

Ants Aasma