How do i a values in a list.
Like lets say i have 5 numbers 1, 2, 6, 23, 5 and i want to store their total inside a variable without having to do it manually.
Because i will make the program let the user input their own values and i cant guess the values.
this is what i got when i searched it up
l = list(range(3))
l.append([3, 4, 5])
print(l)
# [0, 1, 2, 100, 'new', [3, 4, 5]]
CodePudding user response:
If you are trying to allow users to input things to the list, you can try
for i in range(num):
list.append(int(input('Enter a number: ')))
where num is how many inputs you want
and then you can use Python sum() function to find the sum:
total = sum(list)
CodePudding user response:
Simple way:
total = sum(myList)
CodePudding user response:
What you need to do is to loop through all the numbers and calculate the total.
myList = [1, 2, 6, 23, 5]
total = 0
for number in myList:
total = total number
print(total)
Output
37
Alternative Method
myList = [1, 2, 6, 23, 5]
total = sum(myList)
print(total)
Output
37
I hope this answer's your question! If you need any clarifications just feel free to comment below ^-^ I'm here to help!
