12
votes

I'm interested in the thought process that led to this. To me, a relative newbie, it seems hampering, since it prevents "chaining" of list processing (e.g. mylist.reverse().append('a string')[:someLimit]). I imagine it might be that "The Powers That Be" decided that list comprehension is a better paradigm (a valid opinion), and so didn't want to encourage other methods - but it seems perverse to prevent an intuitive method, even if better alternatives exist.

Note that I'm not complaining (I'm sure there is a sensible reason, I'm just interested in what it is!), nor looking for a solution (the comments here were very instructive) - just looking for some context, and a deeper understanding of the language's design process.

3

3 Answers

18
votes

The general design principle in Python is for functions that mutate an object in-place to return None. I'm not sure it would have been the design choice I'd have chosen, but it's basically to emphasise that a new object is not returned.

(GvR's (our Python BDFL) states the design choice here: http://mail.python.org/pipermail/python-dev/2003-October/038855.html)

9
votes

I can't speak for the developers, but I find this behavior very intuitive.

If a method works on the original object and modifies it in-place, it doesn't return anything, because there is no new information - you obviously already have a reference to the (now mutated) object, so why return it again?

If, however, a method or function creates a new object, then of course it has to return it.

So l.reverse() returns nothing (because now the list has been reversed, but the identfier l still points to that list), but reversed(l) has to return the newly generated list because l still points to the old, unmodified list.

EDIT: I just learned from another answer that this principle is called Command-Query separation.

4
votes

One could argue that the signature itself makes it clear that the function mutates the list rather than returning a new one: if the function returned a list, its behavior would have been much less obvious.