[] and NoneType

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Wed Aug 21 04:03:05 CEST 2002

bzhang at sangamo.com (beilin) writes:
> Could anyone explain to me why [].append("test") returns None? What is
> the difference between the following two?
> >>> a = []

Binds the variable 'a' to a newly constructed empty list

> >>> a.append("test")

Call the append method on a, discarding the return value (the return
value happens to always be None).  Calling the append method also has
the side effect of sticking the string "test" into the list it's called on.

> >>> print a
> ['test']

prints the contents of the list after the append call has modified it.

> and 
> >>> a = [].append("test")

Constructs a new empty list and calls the append method on it, which
as above sticks the string "test" into the list and returns the value None.
Binds the return value to the variable 'a'.

> >>> print a
> None

Prints the value of 'a', which is None.

More information about the Python-list mailing list