Home >Backend Development >Python Tutorial >Why Do Python List Mutation Methods Return `None`?

Why Do Python List Mutation Methods Return `None`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 12:49:12716browse

Why Do Python List Mutation Methods Return `None`?

Why List Mutations Return None in Python

When manipulating Python lists with methods like append, sort, extend, remove, clear, and reverse, one encounters a curious behavior: these operations modify the list in-place and return None instead of the updated list.

This design choice was driven by a fundamental principle in Python: functions that mutate an object in-place should return None. This serves to highlight the fact that a new object is not created during such operations.

Guido van Rossum, Python's creator, explains his rationale in detail on the Python-Dev mailing list. He argues against chaining side-effects on a single object in a concise manner, as it can obscure the reader's understanding of the code's intent. For example, consider the following code:

x.compress().chop(y).sort(z)

This is equivalent to:

x.compress()
x.chop(y)
x.sort(z)

Van Rossum contends that the second form is clearer, as it explicitly shows that each operation is applied to the same variable, x.

On the other hand, the use of chaining is reserved for operations that return new values, such as string processing operations:

y = x.rstrip("\n").split(":").lower()

Although certain library modules, like pstat, may encourage the chaining of side-effect calls, Van Rossum asserts that this practice is discouraged for new additions to the standard library.

The above is the detailed content of Why Do Python List Mutation 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