//
you're reading...
python

Sequence multiplication and reflected operands

My 2 cents for Hidden features of Python

>>> 'xyz' * 3
'xyzxyzxyz'
>>> 
>>> [1, 2] * 3
[1, 2, 1, 2, 1, 2]
>>> 
>>> (1, 2) * 3
(1, 2, 1, 2, 1, 2)

We get the same result with reflected (swapped) operands

>>> 3 * 'xyz'
'xyzxyzxyz'

It works like this:

>>> s = 'xyz'
>>> num = 3

To evaluate an expression s * num interpreter calls s.__mul__(num)

>>> s * num
'xyzxyzxyz'
>>> s.__mul__(num)
'xyzxyzxyz'

To evaluate an expression num * s interpreter calls num.__mul__(s)

>>> num * s
'xyzxyzxyz'
>>> num.__mul__(s)
NotImplemented

If the call returns NotImplemented then interpreter calls
a reflected operation s.__rmul__(num) if operands have different types

>>> s.__rmul__(num)
'xyzxyzxyz'

See http://docs.python.org/reference/datamodel.html#object.__rmul__

Discussion

No comments yet.

Leave a comment

Categories