Home >Backend Development >Python Tutorial >Why Do Python's List Mutating Methods Return `None`?

Why Do Python's List Mutating Methods Return `None`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 12:23:11227browse

Why Do Python's List Mutating Methods Return `None`?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn