Implicit conversion to boolean in if and while statements

Chris Angelico rosuav at gmail.com
Sat Feb 9 01:05:54 CET 2013


On Sat, Feb 9, 2013 at 6:58 AM, Rick Johnson
<rantingrickjohnson at gmail.com> wrote:
> I'm a bit unnerved by the sum function. Summing a sequence only makes sense if the sequence in question contains /only/ numeric types. For that reason i decided to create a special type for holding Numerics. This will probably result in many complaints from lazy people who want to use only one Sequence type, which holds mixed types, THEN jamb nothing but numeric types into it, THEN have a sum method that throws errors when it encounters a non-numeric type!!! I say, too bad for you.


Most assuredly not. The sum builtin works happily on any sequence of
objects that can be added together. It works as an excellent flatten()
method:

>>> nested_list = [["q"], ["w","e"], ["r","t","u"], ["i","o","p"]]
>>> sum(nested_list,[])
['q', 'w', 'e', 'r', 't', 'u', 'i', 'o', 'p']
>>> nested_list
[['q'], ['w', 'e'], ['r', 't', 'u'], ['i', 'o', 'p']]

I'm not sure what your definition of a numeric type is, but I suspect
that list(str) isn't part of it.

ChrisA



More information about the Python-list mailing list