Python’s sum function on steroids

Radek Bezvoda
1 min readMay 3, 2021

We’ve all been using the builtin sum function to add up integers or floats from lists or tuples for years, since our Python journey started. It’s well taught but a little boring feature of the language, right?

Well, maybe not so boring after all. Sum is able to add up not only numbers, but other elements too, we just need to set a starting point for that.

Consider this list:

my_list = [[1,2], [3,4]]

It would be neat if we can add up the integers from the inner lists together.

We can use the sum function for this flattening of list object this way:

sum(my_list, start=[])

The start parameter specifies what value should we start with. By default, it’s 0, but we can easily change it to an empty list.

What we get back, is a flattened list:

[1, 2, 3, 4]

And, this list we can easily sum as we are used to.

So, the resulting code looks like this:

sum(sum(my_list, start=[])) # 10

The same trick works for other objects that know the + operator, with the exception of str. Enjoy!

--

--