[Python-ideas] Intermediate Summary: Fast sum() for non-numbers

David Mertz mertz at gnosis.cx
Thu Jul 18 20:42:51 CEST 2013


OK... I have an update to my experiment. I asked by email another friend of
mine (also middle-aged adult, well-educated, a doctorate in humanities FWIW
[like me]), this one has had an introductory exposure to programming, and
in Python specifically, but just one semester-long intro course (the
wonderful edX MIT Intro to CS, a few months ago).

This is what I sent her (I also attached my report of the physical
experiment that I subjected our mutual friend to):

Before you read the long post below, just consider this part up here and
tell me what you think.  Consider this Python code:

list_of_lists = [ [4, 5, 6, 2, 1],
                  [6, 12, 13, 19, 100],
                  [100, 200, 300]
                ]
result = sum(list_of_lists)

You may not have used the built-in function sum before.  But here is an
example of its most common usage:

>>> sum([10,20,30,40])
100

So the question is: what is your intuition about what 'result' *should* be?
If you happen to know that Python does one thing, but feel like it *should* do
a different thing, that is very interesting too.  One answer that you might
feel is that it doesn't make sense and there should be an exception raised
on that line.  For example, this happens:

>>> sum(['foo','bar'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'


Her reply: "I would want an exception raised cause it doesn't make sense."

Yes, I know the code actually *does* raise an exception already; but I
spoke with her to, and her answer isn't "it should raise an exception
because the start= is missing" ... at a beginner level she explicitly means
"It doesn't make sense to sum lists, only numbers."

Actually, this makes me think even more strongly that an identity element
for a type is necessary for sum() to make ANY sense.  You need to have an
implied identity as the starting state... yes, in principle we could let
sum infer the list identity [], but for other types where that doesn't even
exist, it seems even worse... even where it will work for technical reasons.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130718/5e167f77/attachment.html>


More information about the Python-ideas mailing list