Inconsistent reaction to extend

Christophe chris.cavalaria at free.fr
Fri Sep 9 07:43:40 EDT 2005


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. 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.



More information about the Python-list mailing list