ramakrishna reddy wrote: > Hi All, > > I know > >> sum([1,2,3]) returns 6. > > But sum with [] 'empty list' as second parameter returns as below. > >> sum([[1,2,3], [3,4,5]], []) returns [1, 2, 3, 3, 4, 5] > Can any one please explain this logic ? I searched in google but could not > find the suitable answer.
sum() adds up whatever you feed it (unless it's a string). A simplified pure-python implementation is >>> def mysum(iterable, start=0): ... result = start ... for value in iterable: ... result = result + value ... return result ... When you feed it a list of numbers >>> mysum([1, 2, 3, 4]) 10 it calculates the sum, when the list is empty it returns the start value >>> mysum([]) 0 ...whatever it may be: >>> mysum([], mysum) <function mysum at 0x7fd5ee36a510> >>> sum([], sum) <built-in function sum> When you feed it a list of lists it tries to add 0 + first_list and fails >>> mysum([[1,2], [3,4]]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in mysum TypeError: unsupported operand type(s) for +: 'int' and 'list' However when you provide a list as the start value that list and the lists in the `iterable` argument are concatenated >>> mysum([[1,2], [3,4]], []) [1, 2, 3, 4] >>> mysum([[1, "a"], [3, 4.0]], [42]) [42, 1, 'a', 3, 4.0] ...because concatenation is what the + operator is written to do >>> ["foo", "bar", "baz"] + ["ham", "spam"] ['foo', 'bar', 'baz', 'ham', 'spam'] for Python's built-in lists. If you feed your own objects to sum() you are completely free how you implement + -- if you have it remove files from your hard drive then that's what sum() will do when you try to calculate the sum: >>> class Remove(list): ... def __radd__(self, other): ... for name in self: ... print("Deleting file", name) ... >>> sum([Remove(["important.txt", "keepsafe.doc"]), Remove(["nice_pic.jpg"])]) Deleting file important.txt Deleting file keepsafe.doc Deleting file nice_pic.jpg _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor