Accumulating the result in a for loop in Python
To find the sum of all elements, you need to add them up sequentially in each iteration of the loop. And the result obtained should be written to a separate variable.
Let us have a list lst
:
lst = [1, 2, 3, 4, 5]
Let's find the sum of its elements. First, we declare an empty variable res
, in which the sum of all elements will be successively accumulated. Then, in the body of the cycle, we write the addition of each element to it:
res = 0
for el in lst:
res = res + el
print(res) # 15
You can write the addition of an element in a more concise form using the special operator +=
:
res += el
Accumulation can also be used to merge elements into one string. Only in this case, we will assign an empty string to the variable res
instead of 0
. We will merge all the elements of the list into it:
lst = ['1', '2', '3', '4', '5']
res = ''
for el in lst:
res += el
print(res) # '12345'
Given a list:
tst = [1, 2, 3, 4, 5]
Find the sum of the squares of the elements of this list.
Given a list:
tst = ['a', 'b', 'c', 'd', 'e']
Use a loop to concatenate the elements of this list into a string:
'abcde'
Given a list:
tst = [1, 2, 3, 4, 5]
Use a loop to combine the elements of this list into a number:
12345