Appending to []

Terry Reedy tjreedy at udel.edu
Sat Apr 21 12:10:34 EDT 2012


On 4/21/2012 9:08 AM, Dave Angel wrote:
> 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')

Sequential appends are nearly always done within a loop.

>> would be possible with a containing the resulting list
>>
>> ['x', 'y', 'z'].

> 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.

Guido having decided to consistently not return mutated objects,
perhaps partly on the basis that the caller could already have a
reference to the object, it was easy a decade or more later to add 
various methods/functions, including pop() and next(), that mutate by 
removing and returning an object, while remaining consistent with the rule.

-- 
Terry Jan Reedy




More information about the Python-list mailing list