Python Forum
Sum of List - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Sum of List (/thread-19624.html)



Sum of List - nag_sathi - Jul-07-2019

Hi,

I have wrote a python program to sum the numbers in a list.However its giving answer one.

Please advise.

MyList = []
Number =  int(input("Please enter number:"))
for i in range(1, Number + 1):  
    value = int(input("Enter Numbers %d:" %i))
MyList.append(value)

total = sum(MyList)

print("Sum of num:", total)
output

[C:\Practice>py Sumlist.py
Please enter number:4
Enter Numbers 1:1
Enter Numbers 2:2
Enter Numbers 3:3
Enter Numbers 4:1
Sum of num: 1



RE: Sum of List - SheeppOSU - Jul-07-2019

just do this
total = 0
for x in MyList:
    total += x



RE: Sum of List - Yoriz - Jul-07-2019

MyList.append(value) is not inside of the for loop


RE: Sum of List - DeaD_EyE - Jul-07-2019

(Jul-07-2019, 04:33 PM)SheeppOSU Wrote: just do this
total = 0
for x in MyList:
    total += x

Is not Pythonic. You're doing it wrong.
Also sum is much faster because it's implemented in C.
If you have a very long list, the for-loop is much slower.


RE: Sum of List - nag_sathi - Jul-08-2019

Hi All,

I have done slight modification in code and its working. Thanks all for the response.

MyList = []
Number =  int(input("Please enter number:"))
for i in range(1, Number + 1): 
    value = int(input("Enter Numbers:")) 
    MyList.append (value)
    total = sum(MyList)

print("Sum of num:", total)
output

Please enter number:5
Enter Numbers:5
Enter Numbers:2
Enter Numbers:3
Enter Numbers:5
Enter Numbers:5
Sum of num: 20



RE: Sum of List - Yoriz - Jul-08-2019

total = sum(MyList) does not need to be in the for loop, this means it calculates the sum for every loop, the sum is only required after the loop has finished.


RE: Sum of List - perfringo - Jul-08-2019

Some additional nitpicking as well Smile

It's always good idea to stick naming conventions defined in PEP8.

So instead MyList use my_list (BTW - my_list is not very good name as it doesn't give any hint what list it is and for what purpose it will be used, 'numbers' could be better, especially if you use 'number' as variable name: you append number to numbers numbers.append(number))

Same applies to uppercase 'Number' (use number).

If using 3.6 <= Python then using f-strings is recommended:

print(f'Sum of numbers: {sum(numbers)}')