append on lists

Armin a at nospam.org
Mon Sep 15 16:45:38 EDT 2008


Chris Rebert wrote:
> On Mon, Sep 15, 2008 at 1:24 PM, Armin <a at nospam.org> wrote:
>>
>> Hi,
>>
>> just a dumb question.
>>
>> Let a = [1,2,3,4,5]
>>
>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ??
> I'll assume the presence of the 6 is a typo.

Sorry, that's the case.

> 
> Because .append() mutates 'a' and appends the item in-place rather
> than creating and returning a new list with the item appended, and
> it's good Python style for mutating methods to have no return value
> (since all functions must have some return value, Python uses None
> when the function doesn't explicitly return anything).

Yes, but this is very unconvenient.
If d should reference the list a extended with a single list element
you need at least two lines

a.append(7)
d=a

and not more intuitive d = a.append(7)

--Armin


> 
> If you print 'a' after doing the .append(), you'll see it's changed to
> your desired value.


> 
> Regards,
> Chris
> 
>> --Armin
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>



More information about the Python-list mailing list