Skip to main content
The *= operator is an augmented assignment operator that performs in-place multiplication or sequence repetition. It evaluates the product of the left and right operands and binds the resulting value back to the left operand’s identifier.

Syntax

While logically equivalent to x = x * y, the *= operator evaluates the left operand only once and handles memory allocation differently depending on the mutability of the left operand.

Underlying Mechanics

When the Python interpreter encounters x *= y, it determines the execution path based on the data type of x:
  1. __imul__(self, other): Python first checks if the left operand implements the “in-place multiply” magic method. If it does (which is typical for mutable objects), the object modifies its own data in memory and returns self. The variable x remains bound to the exact same memory address.
  2. __mul__(self, other): If __imul__ is not implemented (which is strictly true for immutable objects), Python falls back to the standard multiplication method. It evaluates x * y, allocates a completely new object in memory for the result, and rebinds the identifier x to this new object.

Behavior by Type

Immutable Types (Integers, Floats, Strings, Tuples)

Because these types cannot be changed after creation, *= acts as syntactic sugar for x = x * y. A new object is created, and the reference is updated.

Mutable Types (Lists, Bytearrays)

For mutable sequences, *= performs in-place repetition. The existing object is extended with copies of its own contents, preserving the original memory address and affecting any other variables referencing that same object.

Type Restrictions

The right operand must be an integer when the left operand is a sequence type (string, list, tuple). Attempting to use *= with a sequence and a float will raise a TypeError. For numeric types, standard implicit type coercion applies (e.g., an int multiplied by a float using *= will rebind the variable to a new float object).
Tired of Poor Python Skills? Fix That With Deep Grasping!Learn More