Trouble with Python sum function

  • Comp Sci
  • Thread starter mr.me
  • Start date
  • #1
49
0
I don't know why we have to write a sum function for python when there already is one but
this is supposed to sum a list with varible values and I don't understand why it doesn't work, can someone help explain there error, I believe that I am not giving proper values to the line that adds but I don't realize why<



The Attempt at a Solution



Code:
def sum_list (a_list):
    length = len(a_list)
    counter = 0
    total= 0
    
    while(counter < length):
                              
        (a_list[counter] +total)          
    
        counter = counter + 1
    total = total + counter    
    return total      



#testing the functions
my_list = [3,3,3]


print sum_list(my_list)
 

Answers and Replies

  • #2
34,692
6,396
I don't know why we have to write a sum function for python when there already is one but
this is supposed to sum a list with varible values and I don't understand why it doesn't work, can someone help explain there error, I believe that I am not giving proper values to the line that adds but I don't realize why<



The Attempt at a Solution



Code:
def sum_list (a_list):
    length = len(a_list)
    counter = 0
    total= 0
    
    while(counter < length):
                              
        (a_list[counter] +total) <<< Problem is here         
    
        counter = counter + 1
    total = total + counter    
    return total      



#testing the functions
my_list = [3,3,3]


print sum_list(my_list)
Your while loop isn't right. Python evaluates a_list[counter] + total for each element in the array, but you aren't storing the value anywhere.

You need something like this:
total = total + a_list[counter]

Then get rid of the line that says total = total + counter
 
  • #3
49
0
Thanks that's fixed.

To understand my mistake and clarify; is it fair to say that every time the loop ran it was adding 3 to zero then chucking that value into nothing as opposed to saving it, that's why the print was 3?

Again thankyou, I learn more here with a few of my mistakes and all your replies then my instructors teach.
 
  • #4
34,692
6,396
Thanks that's fixed.

To understand my mistake and clarify; is it fair to say that every time the loop ran it was adding 3 to zero then chucking that value into nothing as opposed to saving it, that's why the print was 3?
Yes, that's exactly what was happening.
Again thankyou, I learn more here with a few of my mistakes and all your replies then my instructors teach.
You're welcome! We enjoy being able to help out.
 

Related Threads on Trouble with Python sum function

Replies
2
Views
5K
  • Last Post
Replies
4
Views
392
  • Last Post
Replies
2
Views
752
Replies
8
Views
495
Replies
2
Views
379
Replies
1
Views
1K
Replies
1
Views
5K
Replies
11
Views
1K
Replies
1
Views
4K
Top