append method

Dave Angel d at davea.name
Wed May 23 15:42:55 EDT 2012


On 05/23/2012 03:13 PM, Emile van Sebille wrote:
> On 5/23/2012 5:23 AM 水静流深 said...
>>  >>> s=[1,2,3]
>>  >>> s.append(5)
>>  >>> s
>> [1, 2, 3, 5]
>>  >>> s=s.append(5)
>>  >>> s
>>  >>> print s
>> None
>>
>> why can't s=s.append(5)
>
> It could, but it doesn't.
>
>
>> ,what is the reason?
>
>
> A design decision -- there's currently a mix of methods that return
> themselves and not.  Mostly is appears to me that mutables modify in
> place without returning self and immutables return the new value.
>
> But that's simply my observation.
>
> Emile
>
>

It's simpler than that.  Methods/functions either modify the object (or
one of their arguments), or return the results, but generally not both. 
So sorted() returns a sorted list without modifying the input.  And the
sort() method modifies the list, but does not return it.  So you're
right that methods on non-mutables must return the new value, since they
can't modify the object.



-- 

DaveA




More information about the Python-list mailing list