sum()
builtin gives you the ability to take a list, say [1, 2, 10]
and find the sum of it as if you had written out 1 + 2 + 10
.The
+
operator is also defined for lists, where if you write out [1] + [2] + [10]
you'll get a list back: [1, 2, 10]
What happens if we put these two observations together? Can we
sum()
a list of lists to get one flattened list?Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print sum([[1],[2],[10]]) Traceback (most recent call last): File "<stdin>", line 1, inNope. sum() internally starts with "0 + (first element of sequence)" so you can only pass things that can be added to integers.TypeError: unsupported operand type(s) for +: 'int' and 'list' >>>
2 comments:
Would that work as expected in Ruby?
As far as I can tell, Ruby doesn't have a direct equivalent of the sum() built-in. You can make it work with `foo.inject([]){|acc,i| acc+i}` because you pass the initial value yourself. For the trivial example above, `foo.flatten` would be just as good.
I think Python's sum is limited to integers so that the return type is defined for an empty list. Otherwise you can't distinguish between an empty list-of-lists or an empty list-of-ints.
Post a Comment