Home >Backend Development >Python Tutorial >Why Do Python's List Modification Methods Return `None` Instead of the Modified List?

Why Do Python's List Modification Methods Return `None` Instead of the Modified List?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 21:35:10435browse

Why Do Python's List Modification Methods Return `None` Instead of the Modified List?

Why do Python's List Modification Methods Return None?

Python's list modification methods, such as append, sort, and extend, have the peculiar behavior of returning None rather than the modified list itself. This design decision has sparked curiosity among programmers.

In Java, for instance, list.sort() returns the sorted list, allowing developers to chain method calls conveniently. But in Python, this chaining is not possible, raising the question: why did the designers of Python make this choice?

Design Principle: Emphasizing In-place Modification

One fundamental design principle in Python is that functions that mutate objects in-place should return None. This subtly conveys that no new object is returned.

Guido van Rossum's Perspective

Guido van Rossum, the creator of Python, explained the rationale behind this decision on the Python-Dev mailing list. He suggests that returning None discourages a "threat to readability" posed by the chaining of multiple side-effect calls.

In the following example, the chaining form:

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

requires intimate knowledge of each method in the chain. The second form:

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

is more explicit, making it clear that each method acts on the same object. This helps maintain the clarity of the code, especially when working with unfamiliar classes or methods.

Exceptions to the Rule

While the general principle is for in-place modifications to return None, there are exceptions:

  • Operations that return new values, such as string processing operations, like rstrip() and split(), return the modified or processed string, allowing for chaining.

However, as van Rossum notes, it's important to limit chaining to such operations that return new values to avoid confusion and readability issues.

The above is the detailed content of Why Do Python's List Modification Methods Return `None` Instead of the Modified List?. 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