sequence multiplied by -1

Steven D'Aprano steve at
Sun Sep 26 09:56:59 CEST 2010

On Sat, 25 Sep 2010 23:46:57 -0700, Paul Rubin wrote:

> Steven D'Aprano <steve at> writes:
>> I'm surprised that you think that you should be able to apply arbitrary
>> mathematical operations to strings *before* turning them into an int
>> and still get sensible results. That boggles my mind.
> I think the idea is you should not be able to do mathematical operations
> on strings, and if you try to do one, Python should raise an exception,
> rather than using hokey analogies to guess at what you were trying to
> do.  If you want to replicate a sequence, introduce a function with a
> name like "replicate", rather than overloading an arithmetic operator.

But * isn't a mathematical operation on sequences. It's a repetition 
operator. And repetition isn't a "hokey analogy" of multiplication -- 
you've got it completely backwards. Multiplication is a generalisation of 
repetition, and sequence repetition is more fundamental than mathematical 
multiplication. Long before anyone said 2.3 * 5.7 people were able to 
talk about "two bags of wheat, and another two bags of wheat, and repeat 
six more times". That's how multiplication was invented -- from repeated 
addition. Think of writing numbers as tallies, before the invention of 
arabic numerals. III groups of II would be IIIIII.

The semantics of list.index() and str.index() are not quite the same 
(string indexing finds substrings, while list indexing does not find 
sublists). So what? We have classes and modules and namespaces so that 
you don't need every function to have a unique. It's okay that the index 
method behaves slightly differently when operating on strings and lists, 
and it's okay for the * operator to behave slightly differently too.

It is true that there's a certain class of coders who apparently like 
line-noise, and so they overload operators to do arbitrary things with no 
concern about familiarity with common convention or readability:

# sort the sequence by length
my_seq ** len

But this is bad because there's no convention for exponentiation being 
related to sorting, and so the code is obscure and unintuitive. Without 
the comments, you would have no idea what the line did. But that's just 
the same as doing this:

def raise_to_power(alist, key):
    return alist

This is dumb whether you overload the ** operator or write a function 
called "raise_to_power".

There's nothing obscure or unintuitive about "spam"*3 = "spamspamspam", 
and the fact that it doesn't do the same thing as int("spam")*3 is a 
foolish argument.


More information about the Python-list mailing list