Inconsistent reaction to extend

Robert Kern rkern at ucsd.edu
Fri Sep 9 06:06:43 EDT 2005


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...
> 
> On the other hand, try
> 
> p=range(4).extend([1,2])
> 
> Then, p HAS NO VALUE (NoneType).
> 
> With append the behaviour is similar. I didn't try other methods, but
> I suspect that it won't improve.
> 
> WHY?

.append(), .extend(), .sort() (as well as .update() for dictionaries)
all are methods whose *only* effect is to modify the object in-place.
They return None as a reminder that they do modify the object instead of
copying the object and then modifying the copy. From the FAQ[1] with
respect to .sort():

"""This way, you won't be fooled into accidentally overwriting a list
when you need a sorted copy but also need to keep the unsorted version
around."""

[1]
http://www.python.org/doc/faq/general.html#why-doesn-t-list-sort-return-the-sorted-list

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list