I am progressing slowly through the course forcing myself to understand each bit of information before moving on. A year ago I was finishing up a javascript-based nanodegree after receiving a scholarship with another online company and the pace of the course did not allow me that luxury.
In “regular” addition 4 + 3 = 7, 3 + 4 = 7. I know this question isn’t addition related but it is about order, please tell me why when looping through
for element in a list:
sum_list += element
results in a different answer than the reverse (element += sum_list).
sum_list = 0
for element in a list:
sum_list += element
Try to understand, I assigned a variable ‘sum_list’ to zero. And looping through the list element and adding it’s value on ‘sum_list’ variable.
Here, element variable describes the values which are on the list, that’s why you can’t reverse it.
Let’s take an example,
list_val = [1, 2, 3]
sum_list = 0
for element in list_val:
sum_list += element
print(sum_list) #output: 6
In the 1st loop:
value of ‘element’ variable is 1
i.e. sum_list = sum_list(0) + element(1)
In the 2nd loop:
value of ‘element’ variable is 2
i.e. sum_list = sum_list(1) + element(2)
In the 3rd or last loop:
value of ‘element’ variable is 3
i.e. sum_list = sum_list(3) + element(3)
So, the final value of sum_list = 6
and element = 3
I think that will clear your concept, why we can’t reverse the variables.
Another way to think about this is that the variable on the left ‘takes’ the addition and the variable on the right ‘gives’ the variable that is being added.
so
sum_list = 1
list_of_elements = [1, 2, 3]
for element in list_of_elements:
sum_list += element
will result in sum_list = 7 and list_of_elements=[1, 2, 3]
while
sum_list = 1
list_of_elements = [1, 2, 3]
for element in list_of_elements:
element += sum_list
will result in sum_list = 1 and list_of_elements=[2, 3, 4]
The phrase ‘give with the right hand and receive with the left hand’ might help.
Your confusion stems from the fact that you are treating the = sign in math the same as the = sign in Python. In math, = is used to form a statement, or an equation. In Python, the = sign is known as the assignment operator. It’s job is to take the value computed on the right side of the assignment operator and assign it to the variable on the left side. There is no such concept in math as far as I know. So when you switch the variables, in essence you are switching the variable which is to be used for computation, and the variable which is to be used for storing that computation.