Re: append method

Guido.van.Rossum@cwi.nl
Mon, 07 Mar 1994 23:31:58 +0100

>
> >>> list=[100,fib(100),200,fib(200)]
> >>> list
> [100, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], 200, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]]
> >>> list.append(300,fib(300))
> >>> list
> [100, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], 200, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144], (300, [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233])]
>
> Why are there parenthesis around the appended element?

list.append() always appends exactly one element to the list. The
call list.append(300, fib(300)) adds a single element: the *tuple*
(300, fib(300)). If you want to add two elements, call append()
twice:

list.append(300)
list.append(fib(300))

or use list concatenations, as follows:

list = list + [300, fib(300)]

Note that the latter has different semantics if the object pointed to
by list is also known by another name -- the first solution modifies
the object, so the change is visible via both names, while the second
breaks the binding and assigns a different object to list while
leaving the other object and binding untouched.

If you really want to append a list to another list, you can do the
following:

list[len(list) : ] = [300, fib(300)]

This assigns [300, fib(300)] to the empty slice at the end of list.
You can't use list[:] nor list[-0:] since these would both replace the
entire list. To insert a list in front of a list, you can use

list[:0] = [300, fib(300)]

though...

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>