Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What does *= mean?

Tags:

python

In Python, what does it mean when *= is used. For example:

for i in xrange(len(files)):
    itimes[i,:,:] *= thishdr["truitime"]
like image 546
k_rose Avatar asked Dec 16 '13 23:12

k_rose


1 Answers

As others have explained, this is roughly an equivalent to:

[object] = [object] * [another_object]

However, it's not exactly the same. Technically, the above calls the __mul__ function, which returns a value, and reassign it back to the name.

For example, we have an object A and multiplying it with B. The process is something like this:

> Call the __mul__ function of object A, 
> Retrieve the new object returned.
> Reassign it to the name A.

Looks simple. Now, by doing *= we're not invoking the method __mul__, but instead __imul__, which will attempt to modify itself. The process is something like this:

> Call the __imul__ function of object A,
> __imul__ will change the value of the object, it returns the modified object itself
> The value is reassigned back to the name A, but still points to the same place in memory.

With this, you're modifying it in-place, not creating a new object.

So what? It looks the same..

Not exactly. If you replaces an object, you created a new place for it in memory. If you modify it in-place, the object location in the memory will always be the same.

Take a look at this console session:

>>> a = [1, 2, 3]
>>> b = a
>>> c = 10
>>> a = a * c
>>> print a
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> b
[1, 2, 3]

If we check the memory address:

>>> id(a) == id(b)

False

Using this, the value of b is unchanged, since a is now just pointing to a different place. But using *=:

>>> a = [1, 2, 3]
>>> b = a
>>> c = 10
>>> a *= c
>>> b
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

And if we check the memory address:

>>> id(a) == id(b)
True

The operation affects b as well. This can be tricky and leading to confusing behaviours, sometimes. But once you understand it, it would be easy to handle.

Hope this helps!

like image 155
aIKid Avatar answered Oct 27 '22 03:10

aIKid