[Python-ideas] The non-obvious nature of str.join (was Re: sum(...) limitation)
Stephen J. Turnbull
stephen at xemacs.org
Tue Aug 12 06:45:05 CEST 2014
Ethan Furman writes:
> Even without an optimization in sum, I'd still rather it did what
> it said: add things together.
But strings aren't additive, they're multiplicative:
>>> "x" "y"
'xy'
>>>
This is a convention deeply embedded in mathematics notation
(multiplicative operators are noncommutative and frequently omitted in
notation, additive operators are commutative and explicit notation
required).
The point is not that it's *wrong* to think that "strings are
additive, so sum *should* apply to iterables of strings". Rather,
it's that it's *not wrong* to think that "strings are non-additive and
therefore not sum()-able". (I'm somewhere in between.)
Why choose '+' as the string multiplication operator, then? Because
programming languages aren't as flexible as mathematics notation,
compromises are often made. Among other things, '*' also has a
meaning for strings (when the other operand is an integer it means
repetition -- oddly enough, it's commutative!) I suppose Guido could
have been a pure algebraist about it and chosen '*' and '^' for
concatenation and repetition, respectively, but that looks odd to me.
The lesson in the end is that although there are many functions that
are convenient to express in Python using operator notation, the
choice of operators should not be taken too seriously in deciding how
they will compose.
More information about the Python-ideas
mailing list