sequence multiplied by -1

Thomas Jollans thomas at jollybox.de
Sat Sep 25 07:45:11 EDT 2010


On Saturday 25 September 2010, it occurred to Yingjie Lan to exclaim:
> Hi,
> 
> I noticed that in python3k, multiplying a sequence by a negative integer is
> the same as multiplying it by 0, and the result is an empty sequence. It
> seems to me that there is a more meaningful symantics.

Um...

for every list l and integer n >= 0:
    len(l*n) == len(l)*n

Multiplying a list by a negative integer should produce a list of negative 
length, which does not exist. IMHO, the only correct behaviour would be to 
raise an exception, though one could argue that there are practical benefits 
for the operation to succeed for any integer operand.

> 
> Simply put, a sequence multiplied by -1 can give a reversed sequence.

For that, we have slicing. A negative step value produces a reverse slice of 
the list. You can't argue that this makes sense, can you

>>> [1,2,3,4][::-1]
[4, 3, 2, 1]
>>> [1,2,3,4][::-2]
[4, 2]
>>> 




More information about the Python-list mailing list