Inconsistent reaction to extend

Antoon Pardon apardon at
Fri Sep 9 13:59:00 CEST 2005

Op 2005-09-09, Christophe schreef <chris.cavalaria at>:
> Antoon Pardon a écrit :
>>>Because creating a new list is potentially very time-consuming and
>>>expensive of memory. Imagine you have a list of 100,000 large objects, and
>>>you want to add one more object to it. The way Python works is that append
>>>and extend simply add that new object to the end of the existing list. The
>>>way you imagined it would work would require Python to duplicate the
>>>entire list, all 100,000 large objects, plus the extra one.
>> This has nothing to do with the need to create a new list.
>> The extend method could just have returned self. Just as sort and reverse could 
>> have done so. This would have made it possible to do things like the following:
>>   lst.sort().reverse()
>> instead of having to write:
>>   lst.sort()
>>   lst.reverse()
> This was done on purpose to avoid a second class of problems.

I know, but I didn't think it was relevant enough for what I was addressing.

> The one 
> where you forget that reverse modifies the list in place. That second 
> class of problems was deemed more dangerous because it works without 
> immediate errors.

I know this is the explanation that is frequently given, but I find
that rather weak. IMO one could argue that the following code
has the same kind of problem as you mention.

lst2 = lst1

If you forget that lst2 is not a copy of lst1 but just an other
name for the same object you are in trouble too and this too
works without immediate errors. So why should lst.sort().reverse()
be so much more dangerous?

Well it doesn't matter much. Python will probably not change in
this respect in the future, so unless you can give me an
argument I haven't heard before I'll just drop this.

Antoon Pardon

More information about the Python-list mailing list