[Python] Why do these list methods (append, sort, extend, remove, clear, reverse) return None...

Discussão em 'Python' iniciado por Stack, Setembro 3, 2025.

  1. Stack

    Stack Membro Participativo

    Many operations on lists that modify the list's contents will return None, rather than returning the list:

    >>> mylist = ['a', 'b', 'c']
    >>> empty = mylist.clear()
    >>> restored = mylist.extend(range(3))
    >>> backwards = mylist.reverse()
    >>> with_four = mylist.append(4)
    >>> in_order = mylist.sort()
    >>> without_one = mylist.remove(1)
    >>> mylist
    [0, 2, 4]
    >>> [empty, restored, backwards, with_four, in_order, without_one]
    [None, None, None, None, None, None]


    Why?

    It prevents "chaining" of list processing (e.g. mylist.reverse().append('a string')[:someLimit]). "The Powers That Be" might've decided that list comprehension is a better paradigm, and so didn't want to encourage other methods - but it seems perverse to prevent an intuitive method, even if better alternatives exist. I'd be interested to know the decisions and tradeoffs that were made when designing the language in this way.


    This question is specifically about Python's design decision to return None from mutating list methods like .append. However, novices often write incorrect code that expects .append (in particular) to return the same list that was just modified. Please do close such questions as a duplicate of this one, however. "The code did the wrong thing because the result was None rather than the list" is something that the OP in these cases should have discovered independently via debugging; creating a proper MRE leaves behind a question like this one - therefore, it can be considered a duplicate.

    See How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)? for the simple question of "how do I append to a list repeatedly?" (or debugging questions that boil down to that problem). This is a new canonical that has been specifically prepared to address the topic with the perspective that beginners lack.

    To get modified versions of the list, see:



    The same issue applies to some methods of other built-in data types, e.g. set.discard (see How to remove specific element from sets inside a list using list comprehension) and dict.update (see Why doesn't a python dict.update() return the object?).

    The same reasoning applies to designing your own APIs. See Is making in-place operations return the object a bad idea?.

    Continue reading...

Compartilhe esta Página