Inconsistent reaction to extend

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Sep 9 12:40:19 CEST 2005


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.



-- 
Steven.




More information about the Python-list mailing list