# sequence multiplied by -1

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Sep 26 03:34:34 CEST 2010

```On Sat, 25 Sep 2010 13:45:11 +0200, Thomas Jollans wrote:

> 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.

Look at the domain of your invariance. It says nothing about negative n,
and nor should it.

> 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.

Since lists of negative length don't exist, we're free to set the
invariance to something which has a less restrictive domain and is more
useful than raising an exception:

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

>> 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]

Why does it not make sense?

I'm more concerned that the simple idiom:

# list L must have at least 5 items, so extend it with None if needed
L.extend([None]*(5 - len(L))

would suddenly break with this proposal.

--
Steven

```