Home > Backend Development > Python Tutorial > When do i += x and i = i + x not equal in Python?

When do i += x and i = i + x not equal in Python?

silencement
Release: 2019-05-25 15:42:04
Original
4423 people have browsed it

When do i += x and i = i + x not equal in Python?

Enhanced assignment statements are often used, because from various learning channels, we can know that i = 1 is often more efficient than i = i 1 (Here = is used as an example. In fact, enhanced assignment statements are not limited to this). Therefore, we will never tire of using incremental assignment statements wherever we can replace ordinary assignment statements to optimize the code. So have we ever thought about the circumstances under which i = 1 is not actually equivalent to i = i 1!!

Example 1: Using enhanced assignment statements:

When do i += x and i = i + x not equal in Python?

Example 2: Use ordinary assignment statements:

When do i += x and i = i + x not equal in Python?

#In the above two examples, a list type object is assigned to variable a, and then variable a is assigned a value. Given variable b, at this time a and b point to the same memory object [1, 2, 3]. Then apply the incremental assignment operator and the ordinary assignment operator respectively to operate the variable b. Judging from the final result, a and b in Example 1 still point to the same memory object after the operation. In Example 2, on the contrary, a and b point to different memory objects respectively, which means that in Example 2, a new memory object is implicitly created.

The above is the detailed content of When do i += x and i = i + x not equal in Python?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template