Why does Python not support the i++ auto-increment syntax and the ++ operator?

In languages ​​such as C/C++/Java, the auto-increment or auto-decrement operations of integer variables are standard, and they can be divided into prefix operations (++i and --i) and postfix operations (i++ and i-- ), there are some subtle differences with each other, and each has a different purpose.

When users of these languages ​​come into contact with Python, they may wonder why it does not provide ++ or -- operations? In my recent post " One Hundred Thousand Whys of Python? ", many students expressed interest in this topic in the questionnaire.

Although the prefix form of ++i may appear in Python, it does not have the "++" auto-increment operator. Here it is just the superposition of two "+" (positive number symbols). As for the suffix form of " ++", it is not supported at all (SyntaxError: invalid syntax).

In this issue of " Why Python ", we will answer from two main perspectives: Why does Python not support the i++ auto-increment syntax? (PS: Self-increment here refers to "self-increment and self-decrease", the same below)

First of all, Python can of course achieve auto-increment, i.e. write as i += 1or i = i + 1, which is also common in other languages.

Although Python uses different magic methods ( __add__()and __iadd__()) under the hood to perform calculations, the superficial effect is exactly the same.

So, our question can be transformed into: why the above two ways of writing will outperform i++ and become the final choice of Python?

1. Python integers are immutable types

i = 1000Different languages ​​treat differently when we define :

  • Languages ​​such as C (writing method int i = 1000) will apply for a piece of memory space, "bind" it with a fixed name i, and write a variable value of 1000 at the same time. Here, the address and type of i are fixed, and the value is variable (within a certain representation range)
  • Python (writing method i = 1000) will also apply for a piece of memory space, but it will "bind" to the number 1000, that is, the address and type of this 1000 are immutable. As for i, it is just a name label attached to 1000, and there is no Fixed address and type

So when we make i "auto-increment" (i = i + 1), they are handled differently:

  • Languages ​​such as C first find the value stored at the address of i, then add 1 to it, and the new value replaces the old value after the operation
  • Python's operation process is to add 1 to the number pointed to by i, then bind the result to a newly allocated memory space, and then "paste" the name label i to the new number. Old and new numbers can exist at the same time, not a replacement relationship

To use an inappropriate analogy: i in C is like a host, and the number 1000 is parasitic on it; and 1000 in Python is like a host, and the name i is parasitic on it. i in C and 1000 in Python, they are parasitic on the underlying memory space...

It can also be understood like this: The variable i in C is a first-class citizen, and the number 1000 is a variable attribute of it; the number 1000 in Python is a first-class citizen, and the name i is a variable attribute of it.

With the above foreshadowing, let's take a look at i++ again, and it is not difficult to find:

  • In languages ​​such as C, i++ can represent the increase of the numeric properties of i, it does not open up new memory space, and it does not generate new first-class citizens
  • In languages ​​such as Python, i++ is meaningless if it is an operation on its name attribute (it can't be in alphabetical order, let's change i to j); if it is understood as an operation on a number ontology, then the situation will be It becomes complicated: it will generate a new first-class citizen 1001, so it needs to be allocated a memory address. If the address of 1000 is occupied at this time, it will involve the recycling of the old object, and the original reference relationship to 1000 will be affected. So we can only open up new memory space for 1001

If Python supports i++, its operation process is more complicated than that of C's i++, and its meaning is no longer "increase the number by 1" (self-increment), but "create a new number" (new). In this case, The "increment operator" doesn't live up to its name.

Python can theoretically implement i++ operations, but it must redefine the "auto-increment operator", and it will also mislead people with experience in other languages, so it's better to let everyone directly write ori += 1 .i = i + 1

2. Python has iterable objects

The main purpose of designing i++ in languages ​​such as C/C++ is to facilitate the use of the three-segment for structure:

for(int i = 0; i < 100; i++){
    // 执行 xxx
}

This kind of program is concerned with the self-increment process of the number itself, and the addition of the number is associated with the execution of the program body.

There is no such way of writing the for construct in Python, it provides a more elegant way:

for i in range(100):
    # 执行 xxx

my_list = ["你好", "我是Python猫", "欢迎关注"]
for info in my_list:
    print(info)

This reflects a different way of thinking. It cares about iterative traversal within a range of values, and does not care about and does not need to artificially add numbers.

Iterables/iterators/generators in Python provide very good iterative/traversal usage and can be a complete replacement for i++.

For example, the above example implements traversal of the values ​​in the list, and Python can also use enumerate() to traverse subscripts and specific values ​​at the same time:

my_list = ["你好", "我是Python猫", "欢迎关注"]
for i, info in enumerate(my_list):
    print(i, info)

# 打印结果:
0 你好
1 我是Python猫
2 欢迎关注

For example, for dictionary traversal, Python provides traversal methods such as keys(), values(), items(), etc., which are very easy to use:

my_dict = {'a': '1', 'b': '2', 'c': '3'}
for key in my_dict.keys():
    print(key)

for key, value in my_dict.items():
    print(key, value)

With such a weapon, where is the use of i++?

Not only that, but it is rarely used in Python. i += 1Or i = i + 1, due to the existence of iterable objects that can be seen everywhere, developers can easily implement operations on a range of values, and there is little demand for accumulating a value.

So, back to the question we started with, in fact, these two "self-increment" writing methods do not beat i++ by much, just because they are general-purpose operations and do not need to introduce new operators, so Python continues a fundamental support. The real winners are iterables of all kinds!

A little summary: Python does not support the auto-increment operator, on the one hand because its integers are first-class citizens of immutable types. If the auto-increment operation (++) is to be supported, it will bring ambiguity; on the other hand, it is mainly because It has a more suitable implementation, namely iterable objects, with good support for traversal operations.

If you think this article is a good analysis, then you should like these articles:

1. Why does Python use indentation to divide code blocks?

2. Is Python's indentation an anti-human design?

3. Why does Python not use a semicolon as a statement terminator?

4. Why does Python not have a main function? Why do I not recommend writing the main function?

5. Why does Python recommend snake-like nomenclature?

Written at the end: This article belongs to the "Why Python" series (produced by Python Cat), which mainly focuses on topics such as Python's syntax, design, and development, and tries to show the charm of Python by starting with "why" questions. charm. Some topics will have a video version, please watch at station B, watch address: video address

The public number [ Python Cat ], this number serializes a series of high-quality articles, including why Python series, Cat Philosophy series, Python advanced series, good book recommendation series, technical writing, high-quality English recommendation and translation, etc. Welcome to pay attention .

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324061562&siteId=291194637