[Tutor] why no chaining?

Alan Gauld alan.gauld at btinternet.com
Sun Apr 12 09:58:41 CEST 2015


On 12/04/15 07:06, Jim Mooney wrote:
> I thought I'd get [2,3,4,5] from this but instead I get nothing. Why isn't
> it chaining?
>
>>>> q = list(set([1,2,3,1,4,1,5,1,5])).remove(1)
>>>> q
>>>>

Because that's just the way it was designed. It's common in
Python for methods that modify an object to return None.
I don't like it either, but that's the way it is.

You need to create a reference to the object then call
the method then use the modified object.

 >>> q = list(set([1,2,3,1,4,1,5,1,5]))
 >>> q.remove(1)
 >>> print q

Aside:
Normally you would use the help() function to find out
how methods work and what they return but sadly the
documentation for the in-place methods doesn't indicate
the return is None. Some of them have a warning that
its "IN PLACE" but remove does not. Which is a pity.

 >>> help([].sort)
Help on built-in function sort:

sort(...)
     L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
     cmp(x, y) -> -1, 0, 1
(END)

 >>> help([].remove)
Help on built-in function remove:

remove(...)
     L.remove(value) -- remove first occurrence of value.
     Raises ValueError if the value is not present.
(END)

Personally I think it would help if the first lines
for these methods read like:

remove(...) -> None
    L.remove...etc

As is the case with functions that return a value:
Help on built-in function pow in module __builtin__:

help(pow)
pow(...)
     pow(x, y[, z]) -> number

     With two arguments, equivalent to x**y.  With three arguments,
     equivalent to (x**y) % z, but may be more efficient (e.g.
     for longs).
(END)




HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list