Puzzled by list-appending behavior

Chris Rebert clp2 at rebertia.com
Thu May 26 01:17:45 EDT 2011


On Wed, May 25, 2011 at 9:46 PM, Uncle Ben <bgreen at nycap.rr.com> wrote:
> In playing with lists of lists, I found the following:
>
> (In 3.1, but the same happens also in 2.7)
>
> list = [1,2,3]
> list.append ( [4,5,6] )

Note the lack of output after this line. This indicates that
list.append([4,5,6]) returned None. Contrast this with, say,
list.pop().

> x = list
> x   ->
>    [1,2,3,[4,5,6]]
> as expected.
>
> But the shortcut fails:
>
> list=[1,2,3]
> x = list.append( [4,5,6] )
> x   ->
>   nothing
>
> Can someone explain this to me?

The append() method does *not* return the now-appended-to list. It is
a mutator method that modifies the list object in-place; per
convention, it therefore returns None to reinforce its side-effecting
nature to the user (the interactive interpreter by default does not
display None expression results); analogous methods in other languages
return void.

list.remove(), list.sort(), and list.extend() similarly return None
rather than the now-modified list.

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list