sequence multiplied by -1

Steven D'Aprano steve at
Sun Sep 26 04:11:55 CEST 2010

On Sat, 25 Sep 2010 06:54:36 -0700, Yingjie Lan wrote:

> For the rule above, how about the
> case to reverse and multiply:
>>>> L*-3 #L reversed and repeated three times
> v.s.
>>>> L[::-1]*3 #L reversed and repeated three times
> The first one is simpler (4 chars v.s. 9 chars). I thought it was also
> intuitive because if you multiply a vector by -1, you should get a
> vector in the reversed direction. 

Reversing the order of elements in a vector does NOT reverse the vector's 
direction. Vector multiplication by a scalar does elementwise 
multiplication. In mathematics and physics:

[1, 2, 3]*5 => [5, 10, 15]
[1, 2, 3]*-1 => [-1, -2, -3] is a reflection of the vector.

It certainly doesn't reverse the order of elements!

[1, 2, 3] => [3, 2, 1] is a rotation, not a reflection.

Python doesn't treat sequences as vectors, since it's a programming 
language and sequences are more general. Instead it performs repetition. 
This is conceptually simple: multiplying a sequence by n *repeats* the 
sequence n times:

L*n = L+L+L+...+L  # n times

where + is concatenation, not elementwise addition. If n is zero, you get 
the empty sequence:

L*0 = an empty sequence of the same type as L

just like you get nothing if you multiply a number by n. If you ask for 
zero copies of a sequence, you get nothing.

The only tricky parts are what to do for fractional values of n, and 
negative values. For practical reasons, the current behaviour is the most 
useful thing to do.

Once you see sequence multiplication as repetition, then the natural 
interpretation of multiplication by a negative value *cannot* be 
reversal, or any other re-ordering or permutation. How many repetitions 
of [1, 2, 3, 4] does it take to give [1, 4, 2, 3]? Answer -- you can't 
get any other permutation by repeating the original.

Singling out reversal as a privileged permutation is just "tacking on" 
extra functionality, for no real benefit. It would be like making:

sorted(my_list) => sequence in sorted order
sorted(my_list, reversed=True) => sequence in reverse sorted order
sorted(my_list, reversed=3) => sequence with every element multiplied by 
3, then sorted

Yes, you could do it, and yes, it might save somebody a line of code 
somewhere, but WTF???

But even if it wasn't, for reasons of backward compatibility, to say 
nothing of the moratorium, it isn't going to change.


More information about the Python-list mailing list