[Tutor] Standard way to append to a list?

Anna Ravenscroft revanna@mn.rr.com
Wed Apr 16 20:57:01 2003


On Wednesday 16 April 2003 18:01, Magnus Lyckå wrote:
> At Tue, 15 Apr 2003 01:44:38 -0400, Brian Christopher Robinson wrote:
> >Say I have:
> >
> >list = [1, 2, 3]
> >
> >What is the standard way to add 4 to the end of the list?  I know:
> >
> >list = list + [4]
> >
> >would work.  What else is there?
>
> You said it yourself in the subject line. Please read
> http://www.python.org/doc/current/lib/typesseq-mutable.html
> etc.
>
> First of all, don't use list as a variable name. It's
> allowed, but bad practice to use builtin type names as
>
> varible names.

<snip lots of really good profiling/speed stuph>

> ...                     l.append(j)
<snip>
> Now "l = l + [j]" only takes 60% more time, but append is still a better
> choice.

One other thing to watch out for. The first time I tried to use append, I 
tried: 
>>> l=l.append(j)                # Don't do this - really!

When I tried to print l, it was now "None"! That's because append returns 
None. I didn't realize it wasn't just a fancy way of saying l=l+[j] and it 
took some discussion with my tutor to figure it out. 

Keep in mind that append directly modifies l, so you don't need to do any 
rebinding... 

Just my $.03 worth...
Anna