Inconsistent reaction to extend

Antoon Pardon apardon at forel.vub.ac.be
Fri Sep 9 07:27:25 EDT 2005


Op 2005-09-09, Steven D'Aprano schreef <steve at REMOVETHIScyber.com.au>:
> On Fri, 09 Sep 2005 11:47:41 +0200, Jerzy Karczmarczuk wrote:
>
>> Gurus, before I am tempted to signal this as a bug, perhaps
>> you might convince me that it should be so. If I type
>> 
>> l=range(4)
>> l.extend([1,2])
>> 
>> l  gives [0,1,2,3,1,2], what else...
>
> That is correct. range() returns a list. You then call the extend method
> on that list. Extend has deliberate side-effects: it operates on the list
> that calls it, it does not create a new list.
>
>> On the other hand, try
>> 
>> p=range(4).extend([1,2])
>> 
>> Then, p HAS NO VALUE (NoneType).
>
> p has the value None, which is also correct. The extend() method returns
> None, it does not create a new list. There is nothing inconsistent about
> it. Unintuitive, perhaps. Unexpected, maybe. But not inconsistent.
>
> [snip]
>
>> WHY?
>
> 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()

-- 
Antoon Pardon



More information about the Python-list mailing list