Why Python's Mutating List Methods Return None
In Python, operations that modify lists, such as append, sort, extend, remove, clear, and reverse, surprisingly return None instead of the updated list. This design decision has generated curiosity and debate.
Guido van Rossum, Python's Benevolent Dictator for Life (BDFL), explains that this principle stems from coding style considerations. Some languages prefer chaining multiple side effects on a single object, as in x.compress().chop(y).sort(z).
Van Rossum believes this chaining can hinder readability for readers unfamiliar with the methods involved. He prefers a more explicit style where side effects are separated and applied directly to the object:
x.compress() x.chop(y) x.sort(z)
This approach makes it clear which object is being modified, promoting understanding.
Van Rossum reserves chaining for operations that return new values, such as string processing operations where the result is a transformed string, as in:
y = x.rstrip("\n").split(":").lower()
This design decision was deliberately implemented to discourage chaining of side-effect calls and emphasize the distinction between in-place modifications and operations that return new objects. While this may seem inconvenient at times, it promotes clarity and consistency in Python coding style.
The above is the detailed content of Why Do Python's List Mutating Methods Return `None`?. For more information, please follow other related articles on the PHP Chinese website!