Skip to content Skip to sidebar Skip to footer

Difference Between Add And Iadd?

I'm not understanding the purpose of the in-place operators like iadd, imul, etc. Many operations have an “in-place” version. The following functions provide a more primitiv

Solution 1:

The "in-place" functions for immutable objects cannot be implemented using an in-place algorithm, while for mutable objects they could be. The simple truth is that immutable objects don't change.

Otherwise, usage of "in-place" versus not "in-place" functions has deep ramifications when considering mutable objects. Consider the following:

>>>A = [1,2,3]>>>B = A>>>id(A)
4383125944
>>>id(B)
4383125944
>>>A = A + [1]>>>id(A)
4383126376
>>>A += [1]>>>id(A)
4383126376

Suppose you are writing some code where it is assumed that B is a soft copy of A (a mutable object). By not using the "in-place" function when modifying A, desired modifications to B can be quietly missed. What makes matters worse, is that quick visual inspection of the code makes it seem that the code (e.g., A = A + [2]) is implemented correctly (maybe it makes sense mathematically). If one really wants to just modify an object and not receive a new object, then the "in-place" function is the right way to go.

Neither is better than the other. Rather there are specific circumstances under which one might be preferred over the other.

Post a Comment for "Difference Between Add And Iadd?"