sum and strings

Rhamphoryncus rhamph at gmail.com
Sat Aug 19 21:42:14 EDT 2006


Bill Pursell wrote:
> Georg Brandl wrote:
> > Paul Rubin wrote:
> > > Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> writes:
> > >> Because of "there should only be one way to do it, and that way should
> > >> be obvious". There are already the str.join and unicode.join methods,
> > >
> > > Those are obvious???
> >
> > Why would you try to sum up strings? Besides, the ''.join idiom is quite
> > common in Python.
>
> One could extend this argument to dissallow the following:
> >>> "foo" + "bar"

It's worthwhile to note that the use of + as the concatenation operator
is arbitrary.  It could just have well been | or &, and has no
relationship with mathematically addition.  Were history different
perhaps Guido would have gone with | or & instead, and we wouldn't be
having this conversation.

It's also worth stressing (not in response to your post, but others)
that sum([[1],[2],[3]], []) is just as bad as attempting to sum
strings, both conceptually (it's not mathematical addition), and
performance-wise.  Don't do it. :)

I believe the prefered method to flatten a list of lists is this:

shallow = []
for i in deep:
    shallow.extend(i)

Yes, it's three lines.  It's also very easy to read.  reduce() and
sum() are not.




More information about the Python-list mailing list