An overview of the

Enhanced assignment in Python is borrowed from C, so the use of these forms is mostly the same as C, which is itself a shorthand for an expression, a combination of binary expressions and assignment statements, such as a += b and a = a + b are consistent, such as the following enhanced assignment statements.

a += b a &= b a -= b a |= b
a *= b a ^= b a /= b a >>=b
a %= b a <<= b a **= b a //=b

That is, enhanced assignment statements apply to any type that supports implicit binary expressions, such as “+” polymorphism: addition of numbers and combination of strings

Digital subtraction

a = 1
a = a + 1
print(str(a))
a += 1
print(str(a))
Copy the code

Example results:

2, 3,Copy the code

String merging

S = 'I'
S = S + ' like '
print(S)
S += 'Python.'
print(S)
Copy the code

Example results:

I like
I like Python.
Copy the code

advantages

  • concise
  • Reduce aaThe execution speed is faster
  • For mutable objects, enhanced assignment automatically chooses to perform the in-place modification operation instead of the slower copy. This raises the question of shared references that we might be dealing with in mutable objects.

The Shared references

What do we do when we want to extend a list, for example by adding a set of elements to the end?

L = [1.2.3]
# Traditional + method
L = L + [4.5]
print(L)
Use the list method extend
L.extend([6.7])
print(L)
Copy the code

The sample results

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7]
Copy the code

The “+” method in the first example, which uses the merge method, requires creating a new object to copy the L on the left to the new list, and then [4, 5] to the new list. The second type of extend adds [4, 5] directly to the end of the memory space list L, which is faster. Enhanced assignment is automatically adopted. The second type of EXTEND, L.xtend ([6, 7]) and L += [6, 7] are equivalent and the best choice. While this method of merging is fast, shared references to mutable objects can be trickier.

L1 = [1.2.3]
L2 = L1
L2 = L2 + [4.5]
print(L2)
print(L1)

print(The '-' * 21)

L1 = [1.2.3]
L2 = L1
L2 += [4.5]
print(L2)
print(L1)
Copy the code

Example results:

[1, 2, 3, 4, 5] [1, 2, 3] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]Copy the code

We can see from the example that if multiple variables are assigned to the same mutable object, we should copy the mutable object before breaking the shared reference structure.