Hello, so I am trying to understand how to sum values through a for loop within python so that I start with a value, and then add to it, and then add the next value to that, and then add the next value to that, and so on, going through all values in my list/folder. I think this would be referred to as a "cumulative sum". So let's say I have a list of numbers:
list = [1,4,6,3,7,5,2,8,9]
I want to iterate over each value in this list and add all values to the previous like so:
for value in list:
1 + value
sum = 1 + value
print(sum)or something like that? I tried this, and it just adds one to each value in the list, when I want a single final cumulative sum produced. I am really confused about if my logic is correct there. Is this how I would carry out this cumulative sum operation? I am trying to take 1, and then add 4, and then add 6 to that, and then add 3 to that sum, and then add 7 to that sum, and so on. I realize one could also just add all of these values at once, but I am trying to understand how to do this with a for loop. Thanks!
python - How to sum all the answers from for loop? - Stack Overflow
Python summing in loop vs sum() performance
python - Get sum of numbers using a Function and For Loop - Stack Overflow
How does sum function work in python with for loop - Stack Overflow
Videos
prices[item] * cart[item] for item in cart is a generator. It produces an iterable, which is what the sum function takes as its first parameter.
for item in cart iterates over each of the keys in the cart dictionary. So in this case, it will iterate over the list ['apple', 'egg'], setting item to each of these in turn. For each iteration, the expression prices[item] * cart[item] looks up the price of an item (prices['apple'] for example) and multiplies it by the quantity of an item (cart['apple'] for example). The generator produces a sequence consisting of the result of computing the value of this expression for each key in cart, and then sum takes that sequence and adds the elements of it together to come up with the final total of the items in cart.
The code that's in the inside of the sum() is a generator expression which is basically syntactic sugar for creating an iterator from another iterator.
In your example the cart variable is an object of type Dictionary which is also an iterator, and the prices[item] * cart[item] part is how each item from the cart (the dictionary keys) is transformed into a new item for the result iterator.
The snippet bill = sum(prices[item] * cart[item] for item in cart) is equivalent to
Copybill = 0
for item in cart:
bill += prices[item] * cart[item]
This can be expressed using a list comprehension and the sum function:
a = int(input('Enter a number plz '))
print(sum(x*x for x in range(a+1)))
Expanded out, this would be equivalent to:
a = int(input('Enter a number plz '))
total = []
for x in range(a+1):
total.append(x*x)
print(sum(x))
Here's a simpler solution:
a = int(input('Enter a number plz '))
lst = []
for i in range(1, a+1):
def func(root):
print('Number', i, 'in square root is', root)
lst.append(root)
func(i*i)
print(f'The sum is {sum(lst)}')
You can create an empty list, then append all the values of root as you iterate through the for-loop. Now we have a list of all of the root values, so we can make use of the built-in sum function to achieve our final product.
Also note that it is not necessary to have your function in the for-loop:
a = int(input('Enter a number plz '))
def func(root):
print('Number', i, 'in square root is', root)
lst.append(root)
lst = []
for i in range(1, a+1):
func(i*i)
print(f'The sum is {sum(lst)}')
By for loop
def sumAll(n):
sum_all = 0
for i in range(1, n+1):
sum_all = sum_all + i
return sum_all
number = int(raw_input("Please enter a number: \n"))
print ("The answer is: ") + str(sumAll(number))
Output:
Please enter a number:
10
The answer is: 55
You can also use list Comprehension:
print sum([i for i in range(number+1)])
Output:
55
You can also use a mathematical series formula:
def sumAll(n):
return n * (n + 1) / 2
you can even do it without a loop:
def sumAll(n):
return sum(range(1,n+1))
print(sumAll(10)) # -> 55
if you insist on using a loop:
def sumAll(n):
s = 0
for i in range(1,n+1):
s += i
return s
but the mathematical solution is simply:
def sumAll(n):
return n * (n + 1) / 2
# in python 3:
# return n * (n + 1) // 2
(there are n elements with an average value of (n+1)/2; this will always be an integer since either n or n+1 is even; the proof by induction is often the first example when math students learn about induction...).
Your code is shorthand for:
test = sum((5 for i in range(5)))
The removal of extra parentheses is syntactic sugar: it has no impact on your algorithm.
The (5 for i in range(5)) component is a generator expression which, on each iteration, yields the value 5. Your generator expression has 5 iterations in total, as defined by range(5). Therefore, the generator expression yields 5 exactly 5 times.
sum, as the docs indicate, accepts any iterable, even those not held entirely in memory. Generators, and by extension generator expressions, are memory efficient. Therefore, your logic will sum 5 exactly 5 times, which equals 25.
A convention when you don't use a variable in a closed loop is to denote that variable by underscore (_), so usually you'll see your code written as:
test = sum(5 for _ in range(5))
You can add a list to the sum function so you can make something like this:
test = sum((1,23,5,6,100))
print("output: ", test)
And you get 135.
So with your "for loop" you get a list and put that list to the sum function and you get the sum of the list. The real sum function uses yield insight and use every value and sum them up.
You are printing the value of variable "c" in the loop. To print only the sum, remove the indentation of "print(c)". And you are doing "=+" but you should do "+=" to obtain the sum.
c=0
for i in range(0,101):
c+=i
print(c)
There's a python function just for this - sum
print(sum([x for x in range(1, 101)]))
Edit: To address the concern about "struggling to understand"
[x for x in range(1, 101)] is called a list comprehension. They are used to create lists in a singular line, without using for loops - python can be a functional programming language after all. [x for x in range(1, 101)] returns a list from 1 to 100, that is-
[1, 2, 3, 4, 5, ......., 99, 100]
We skip 0 because it doesn't count in the sum anyway.
Now if you do sum() on this list, it'll return the sum of all elements in the list.
Hence sum([for x in range (1, 101)]) returns the sum of all numbers from 1 to 100 (inclusive) and print will print the final result.
Why use many lines when few do trick? :)
Remember, List Comprehension and sum() are 2 very important tools in the python toolbox, everyone should know about these 2.