append on lists

Alex Marandon invalid at nowhere.invalid.org
Tue Sep 16 06:15:48 EDT 2008


Armin wrote:
> 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] ??
>>
>> 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.

Hi,

You might be interested in using the + operator instead of append. You 
could also define your own list type, based on the UserList included in 
the standard library.

 >>> from UserList import UserList
 >>> class MyList(UserList):
...     def my_append(self, value):
...         return self + [value]
...
 >>> l = MyList([1,2,3,4])
 >>> l
[1, 2, 3, 4]
 >>> l.my_append(5)
[1, 2, 3, 4, 5]
 >>> l
[1, 2, 3, 4]




More information about the Python-list mailing list