list.clear() missing?!?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Apr 13 07:28:29 EDT 2006


On Thu, 13 Apr 2006 09:11:31 +0200, Fredrik Lundh wrote:

> Peter Hansen wrote:
> 
>> It's not even clear that extend needs two lines:
>>
>>  >>> s = range(5)
>>  >>> more = list('abc')
>>  >>> s[:] = s + more
>>  >>> s
>> [0, 1, 2, 3, 4, 'a', 'b', 'c']
>>
>> Okay, it's not obvious, but I don't think s[:]=[] is really any more
>> obvious as a way to clear the list.
>>
>> Clearly .extend() needs to be removed from the language as it is an
>> unnecessary extension to the API using slicing
> 
> you just flunked the "what Python has to do to carry out a certain operation"
> part of the "how Python works, intermediate level" certification.

So implementation details are part of the language now? 

Out of curiosity, are those things that Python has to do the same for
CPython, Jython, IronPython and PyPy?

Personally, I think it is a crying shame that we're expected to be experts
on the specific internals of the Python interpreter before we're allowed
to point out that "only one obvious way to do it" just is not true, no
matter what the Zen says.

>>> L = []
>>> L.append(0)
>>> L[:] = L + [1]
>>> L[:] += [2]
>>> L[len(L):] = [3]
>>> L.__setslice__(len(L), -1, [4])
>>> L.__setslice__(sys.maxint, sys.maxint, [5])
>>> L += [6]
>>> L
[0, 1, 2, 3, 4, 5, 6]

That's at least seven ways to do an append, and it is a double-standard to
declare that slice manipulation is the One and Only True obvious way
to clear a list, but slice manipulation is not obvious enough for
appending to a list.

No doubt under the hood, these seven ways are implemented differently.
They certainly differ in their obviousness, and I'm willing to bet that
practically nobody thinks that the slicing methods are more obvious than
append. Perhaps we're not Dutch. I daresay one method is better, faster,
or more efficient than the others, but remember the warning against
premature optimisation.

Whenever I see "only one obvious way to do it" being used as a knee-jerk
excuse for rejecting any change, my eyes roll. Nobody wants Python to
turn into Perl plus the kitchen sink, but it isn't as if Python is some
absolutely minimalist language with two objects and three functions. There
is no shortage of "more than one way to do it" convenience methods,
functions and even entire modules. And that's why Python is such a fun,
easy to use language: because most things in Python are just convenient.
When you want to append to a list, or insert into a list, you don't have
to muck about with slices, you call the obvious list method.

And so it should be for clearing all or part of a list.



-- 
Steven.




More information about the Python-list mailing list