Appending to []

Dave Angel d at davea.name
Sat Apr 21 09:08:50 EDT 2012


On 04/21/2012 08:48 AM, Bernd Nawothnig wrote:
> On 2012-04-20, Rotwang wrote:
>> since a method doesn't assign the value it returns to the instance on 
>> which it is called; what it does to the instance and what it returns are 
>> two completely different things.
> Returning a None-value is pretty useless. Why not returning self, which would be
> the resulting list in this case? Returning self would make the
> language a little bit more functional, without any drawback.
>
> Then nested calls like
>
> a = [].append('x').append('y').append('z')
>
> would be possible with a containing the resulting list
>
> ['x', 'y', 'z'].
>
> That is the way I expect any append to behave.
>
>
>

This has been debated here many times.  The python reasoning for most
cases goes something like this:

A function/method on an object may either alter the object, or produce a
new one and return that.  If it does both, the programmer can get
surprised and have a bug that's difficult to notice.

For example, you can either sort() a list, in which case it's done
in-place, returning none.   Or you can call sorted() on it, which
returns a new list, similar to the first, but sorted.



-- 

DaveA




More information about the Python-list mailing list