+ 1
Python - Why does list1 = [1,2,3,4] in this code?
def guess(list1): list2 = list1 list2.append(4) list1 = [5,6,7] print(list1) # outputs [5, 6, 7] print(list2) # outputs [1, 2, 3, 4] list1 = [1,2,3] guess(list1) print(sum(list1)) # outputs 10 (instead of 18) Why does list1 = [1, 2, 3, 4] (instead of [5, 6, 7]) after the line ' guess(list1) ' ?
3 Answers
+ 7
Solus You have defined a local variable called "list1" within the function. Hence, that [5,6,7] list stays within the function.
However, the "list1" you defined in your parameter is what is passed as "list2" the local variable. You have essentially copied the reference of "list1" the parameter. Hence, any alteration to list2 is reflected in the parameter list1.
When you using the function's print statement, you print list1 the local variable. When you sum the list outside the function, you are using list1 the global variable/parameter, which has been altered because list2 shares a reference with THIS list1 and you altered list2.
Hope I was clear.
+ 1
def guess(list1):
list2 = list1 #here list1 refference is assigned to list2 so list2 also [1,2,3]
list2.append(4) so now [1,2,3,4]
list1 = [5,6,7] now list1 is assigned new list and no longer list2 points to list1 so now both separated. And now list1 is new local variable different from passed global variable..
print(list1) # outputs [5, 6, 7]
print(list2) # outputs [1, 2, 3, 4]
print(sum(list1)) #here list1 still points to old one and same to list2 refferenced..
0
đ Prometheus đ¸đŹ
"Hence, any alteration to list2 is reflected in the parameter list1. "
--> okay, so list2 is referencing the PARAMETER list1
--> and the PARAMETER list1 is considered a global variable
When a (local) function variable has the same name as the (global) function parameter, assignment to such (local) function variable does NOT affect the (global) function parameter.
======================================================
FOLLOW UP QUESTION:
How come the following codes won't give the same output?
1)
def guess(list1):
list2 = list1
list2.append(4)
list2.append(5)
list2.append(6)
list1 = [1, 2, 3]
guess(list1)
print(list1) # outputs [1, 2, 3, 4, 5, 6]
2)
def guess(list1):
list2 = list1
list2 + [4,5,6]
list1 = [1, 2, 3]
guess(list1)
print(list1) # outputs [1, 2, 3]
Does referencing only work when modifying the reference variable with a METHOD?