append on lists

Chris Rebert clp at rebertia.com
Mon Sep 15 16:47:53 EDT 2008


On Mon, Sep 15, 2008 at 1:45 PM, Armin <a at nospam.org> 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] ??
>>
>> 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)

And then they'd both reference the same list and you'd run into all
sorts of problems.

The code you'd actually want is:

d = a[:] #copy a
d.append(7)

Or if you're willing to overlook the inefficiency:

d = a + [7]

But that's not idiomatic.

And debating the fundamentals of the language, which aren't going to
change anytime soon, isn't going to get you anywhere.
You may be interested in looking at Python's "tuple" datatype, which
is basically an immutable list.

I'd also suggest you Read The Fine Tutorial, and that your original
question was better suited to IRC or python-tutors
(http://mail.python.org/mailman/listinfo/tutor) than this mailinglist.

Regards,
Chris

>
> --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
>>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list