A=[2,4,8,16]
for i in A:
B = i/2
print(B)
How to sum values coming from a structure " FOR "? how could i to sum 1+2+4+8 ?
A=[2,4,8,16]
for i in A:
B = i/2
print(B)
How to sum values coming from a structure " FOR "? how could i to sum 1+2+4+8 ?
You can have a variable outside and loop and keep adding the values in the list A
A=[2,4,8,16]
B = 0
for i in A:
B = B+ i/2
print(B)
I assume that here you are interested in understanding what is/should be happenning.
Let's start from your input:
A = [2, 4, 8, 16]
You have already found out that to access the elements of A
, you can use a for
loop, and then do whatever you want with each individual element.
To compute the sum of n
numbers, you can use of the associative property of
addition (a + b) + c = a + (b + c)
and the fact that it has a neutral element (0
), to accumulate iteratively the result in a new single variable:
result = 0 # the neutral element
for x in A:
B = x / i
result = result + B
The value of result
is updated at each iteration with the value of result
from the previous iteration summed with B
.
This is equivalent to:
(((0 + B) + B) + B) + ... + B
(as many times as there are elements in A).
Now, you can notice that B
is:
for
loopFor these reason you might replace its only usage with its value:
result = 0 # the neutral element
for x in A:
result = result + x / i
Also, the construct x = x + y
can be written more concisely and efficiently as x += y
(using +=
operator):
result = 0 # the neutral element
for x in A:
result += x / i
Finally, the sum of multiple elements is sufficiently common that in Python the above has been optimized and provided with a separate sum()
function:
sum(x / i for x in A)
which combines a for
generator expression with sum()
.