In both the code snippets, you are initializing total_cost
as 0
.
The loop variable cost
is being used to iterate over the actual_insurance_costs
list. That means, in the first iteration cost
will be assigned the value 1100.0
, in the second iteration it will be assigned the value 2200.0
and so on till the whole list is traversed.
In the first snippet, in every iteration of the loop the following statement is executed:
total_cost += cost
Since numbers are an immutable data type, so using the +=
operator can be considered as being equivalent to:
total_cost = total_cost + cost
In every iteration of the loop, you add the number assigned to cost
to the existing total_cost
and store the result in total_cost
. Once the loop finishes, total_cost
holds the value 30800.0
In the second snippet, in every iteration of the loop the following statement is executed:
cost += total_cost
which can be considered as being equivalent to:
cost = cost + total_cost
In the first iteration, total_cost
is 0
and cost is 1100.0
. After executing the above statement, the result of the addition will be 1100.0
which will be assigned to the cost
variable (as a side note, the original list will not be mutated because cost
just holds the value and not the reference to the list element, but I digress).
In the second iteration, total_cost
is 0
and cost will be 2200.0
(because the second element of the list is 2200.0
. The value assigned to cost
in the last iteration will be overwritten). After executing cost = cost + total_cost
, the value assigned to cost
will be 2200.0
Once the loop finishes, cost
will hold the value 7700.0
(since that is the last element of the list). total_cost
will still be 0
. When you print this variable, print(total_cost)
, the output will be 0
.