List mutation method gotcha - How well known?

Paul Rubin http
Thu Mar 13 11:42:05 CET 2008


"Hendrik van Rooyen" <mail at microcorp.co.za> writes:
> Given the following three lines of code at the interactive prompt:
> 
> foo = [1,2,3,4]
> x = foo.append(5)
> print x
> 
> What will be the output (choose one):
> 4)  Nothing - no output

By Python convention, methods that mutate the object return None, and
also stuff that returns None doesn't generate output at the
interactive prompt.

There is a similar situation with list.sort() which led to the
introduction of the sorted() builtin.

Lately I try to avoid mutation, e.g. by using a generator or listcomp
instead of building up a list with .append()



More information about the Python-list mailing list