# How can I get the sum of all values in a list?

### Question

In the context of this code challenge, how can I get the sum of all values in a list?

One way to get the sum of all the values in a list is to utilize the built-in `sum()` function in Python. This function will take in a list of numerical values, and return the total of all the values.

Another way to sum all values in a list, is to utilize a loop which iterates over every value, and keeps a running total of all the values.

In this code challenge, consider implementing the second method using a loop to sum the values, instead of the first method of using the `sum()` function.

10 Likes

can u give an example of how sum() function works??

The sum function takes one argument. It can be a list, a tuple, or a set.

``````>>> t = (2,5,8,9)
>>> l = [2,5,8,9]
>>> s = {2,5,8,9}
>>> sum(t)
24
>>> sum(l)
24
>>> sum(s)
24
>>>
``````

It can also be an iterator that generates a sequence.

``````>>> sum(range(10))
45
>>> sum(filter(lambda x: x % 2, range(20)))
100
>>> sum(map(lambda x: x ** 2, range(10)))
285
``````
9 Likes
``````def larger_sum(lst1, lst2):
if sum(lst1) >= sum(lst2):
return lst1
return lst2
``````
3 Likes

Why keep giving exercises that require concepts or functions that havenāt even been taught yet in the course?
Feels a bit frustrating, kind of like going to a woodworking course, being taught how to hammer a nail and then being asked to cut the board in half only to be told that you should be using the circular saw you havenāt been taught how to operate (or even that it exists) yet.

I am doing these courses precisely to be taught these basics, being expected to go research on my own (especially when it isnāt even clear that I canāt solve the problem with what Iāve been taught so far) to figure things out kind of defeats the whole purpose of paying for tuition, does it not?

It is understandable that teaching one to figure things out on their own is a valuable thing, but not this early into the course.

12 Likes

1 Like

Yes, Iām following the computing science career path lessons and I donāt recall ever being taught the sum() function.

It may not be required in the solution. At this point we havenāt covered very many built in functions, so it makes sense that it wouldnāt be expected, even if it does pass.

Another question, āHave you studied iteration?ā

2 Likes

Iām not sure, Iām currently at the end of the " Flow, Data, and Iteration" course in the career path, but I only recall control flow, loops and lists.

For this particular exercise I had been trying to do the following:

``````def larger_sum(lst1, lst2):
lst3 = []
for index1 in lst1:
lst2.sort()
lst3.append(index1 + lst2[-1:])
for index2 in lst2:
lst1.sort()
lst3.append(index2 + lst1[-1:])
return lst3
``````

But canāt get the append to work because the second value is a list, not the list element itself, so I get a TypeError and Iām not sure how to call the specific element integer itself for the sum.

Edit: Oh, wow, I just realized I misinterpreted the instructions. I thought you were meant to get the sum of each element of lst1 with the highest value element of lst2 and also the sum of each element of lst2 with the highest element of lst1 and append them to a new list, not simply sum the elements of each list individually and check which is higher. I realize I sound like a crazy person now, my bad.

2 Likes

Not sure what lesson this, but given the name of the function, we can begin to presume multiple list arguments and the largest sum returned.

Even in a naive computation, there would be no need to sort. Iterate each list, tally up the total of each, and return the largest total.

``````def foo(a, b):
u, v = 0, 0
for x in a:
u += x
for x in b:
v += x
if u > v:
return u
return v
``````
3 Likes

Yep, it turned out to be quite simple after I realized what the exercise expected (simple sum of each list and comparing which is greater). Like I said in the edit, I thought it was asking me to add each element of the first list to the highest element of the second list and append the results to a third list, then add each element of the second list to the highest element of the first list and append these results to the third list too, which is why I was sorting them.

I suppose in this case creating a dummy copy of each original list and then using .pop() to get the last value could work, instead of what I was trying, since pop returns the element itself instead of a list containing the last element, like I was trying and failing to do.

1 Like

Nothing this simple would ever require us to destroy the list inputs (or copy them), so `pop` is out of the question.

Mind, if the lists themselves are disposable (meaning the globals that were passed in) then `pop` is the perfect way to destroy them.

``````u, v = 0, 0
while a: u += a.pop()
while b: v += b.pop()
return u if u > v else v
``````

The return line is Pythonās version of a ternary expression. Gloss over this if it is out of the purview. It will come up eventually when you study conditional expressions in greater detail.

Structures take up memory, however small. Nothing takes up less memory than `None`, as I understand. That means that if we are truly destroying the data structures and recovering as much memory as possible, we can, in this function, obliterate them.

``````u, v = 0, 0
while a: u += a.pop()
while b: v += b.pop()
a, b = None, None
return u if u > v else v
``````

edit

Take that back. We need to connect to the global variables to be able eliminate the data structure, itself.

``````>>> m, n = [2, 5, 8], [3, 6, 9]
>>> def bar():
global m, n                 # says we are going to be setting
u, v = 0, 0
while m: u += m.pop()       # mutate
while n: v += n.pop()       # mutate
m, n = None, None           # set
return u if u > v else v

>>> bar()
18
>>> m, n
(None, None)
>>>
``````

Although. `del` comes to mind. Perfect garbage collection tool. Why would we ever give a function this much sway over our data structures?

2 Likes

Hello friend, i know that feeling. But donāt forget that there are many ways to accomplish the goal of an exercise.

DId you try this?

``````def larger_sum(lst1,lst2):
sum1=0
sum2=0
for item1 in lst1:
sum1+=item1
for item2 in lst2:
sum2+=item2
if sum1>=sum2:
return lst1
else:
return lst2
``````
12 Likes

I found this solution too, but tried a lot before. it is the best solution. But correct that the difficulty is now to combine all the past lessons, because even if you know them well individually, now itās time to think about how and when applying them!

Trust me, you are not alone in this. I even think i am more frustrated. But i have come to realize that it comes with the terrain. The fact that you are frustrated is an indication that you are learning (this is what i have convinced myself). In many cases, i feel lost, i feel i am not learning and i feel āwill i ever understand this inside outā? But you know what? As long as we do not allow our frustration to set us back or demotivate us and as long as we keep up the game, we will cross the hurdle and it will start āmaking senseā sooner rather than later.

From my personal observation (i might be wrong), the application of what we learn is going to be mostly on us. What we need is to get familiar will all the necessary basics and start application . Along the line, experience will the that we need.

We could see this more positively by taking our the word, āfrustratedā and replacing it with, āconfusedā.

2 Likes

Interestingly, i did the below. What is however interesting about it is that, before now, i am not sure i have ever come accross the function sum(). I just figured it out and feel that it should work. I feel so happy when it did (even though this exercise dont really seem like something difficult).

What i have realized is that if we put much effort and get familiar with coding, we will be able to cross the Ts and dot the I s on our own at times

``````def larger_sum(lst1, lst2):
if sum(lst1) > sum(lst2):
return lst1
elif sum(lst2) > sum(lst1):
return lst2
return lst1

#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7]))
``````

Not sure the `sum()` function was called for in the instructions, but it definitely does the job of summing a sequence. Itās still important that we can implement a summing algorithm that doesnāt reach for a built-in.

Furthermore, since we return the first list if it is greater than OR EQUAL to the second (summed up), then we only need to test the second list.

``````>>> def larger_sum(a, b):
def sum(s):
y = 0
for x in s:
y += x
return y
u, v = sum(a), sum(b)
return b if v > u else a

>>> larger_sum([1,2,3,4,9], [5,6,7,8])
[5, 6, 7, 8]
>>>
``````

In the above we call the local function, not the global.

2 Likes

Was trying to do all the exercises with list comprehension:
def larger_sum(lst1,lst2):
x= [lst1 if sum(lst1) >= sum(lst2) else lst2]
return x

So I remove the outside line 2. It works fine! Didnāt know that syntax is not only for list comprehension.

`[VALUE]` is a list literal containing one value
What you have there is not list comprehension.
The expression with if and else in it is also unrelated to list comprehension. List comprehension has the ability to skip values, but it does not look like that.

``````>>> [1]
[1]
``````
``````>>> [(x, y)
...  for y in range(10, 13)
...  for x in range(3)
...  if (y + x) % 2 == 0
...  for z in range(5)
...  if z > 3
... ]
[(0, 10), (2, 10), (1, 11), (0, 12), (2, 12)]
``````

It is reasonable to expect it to be possible to have a list comprehension without iteration - because each iteration is like multiplication, and the identity of multiplication is 1, there should therefore be one āiterationā when there are no loops. The python version doesnāt allow that. But the language where it comes from, does:

``````> ["stuff" | True]
["stuff"]
> ["stuff" | False]
[]
``````

In python that would look like:

``````["stuff" if True]  # python will complain, even though it makes sense
``````

(Thatās not what you wrote. You just had a list literal: `["stuff"]`

1 Like