Home > Article > Backend Development > 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:
Example 2: Use ordinary assignment statements:
#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!