Why does line 1 print [1,2,3, "a"] and not just [1,2,3]? is it because of L2 = f2 (L1, 'a')? AS?
def f1(v,y):
v = 4
y += v
return y
def f2(L,x):
L.append(x)
return L
L1 = [1,2,3]
L2 = `f2(L1,'a')`
print(L1) # Line 1
print(L2) # Line 2
a = 2
b = 3
c = f1(a,b)
print(a) # Line 3
print(c) # Line 4
print( f1(L1,1) ) # Line 5
Why does line 1 print [1,2,3, "a"] and not just [1,2,3]? Is it because of L2 = f2 (L1, 'a')? AS?
source to share
This is because when passing an argument to a L1
function f2
, a variable pointer is passed. So when you add a value to a variable L
inside your function, the list changes as well L1
( L
is nothing but a pointer to L1
)
if the function modifies the object passed as an argument, the caller will see the change
Have a look at this
So is it beacuse of the L2=f2(L1,'a')?
yes
Hope it helps!
source to share
Let L = [1,2,3].
you want to add "a" to this list
eg L.append ('a')
then the list will be L = [1,2,3, 'a']. R8?
The same happens here using the function f2 (L, 'a')
The function f2 takes a list and the value of 'a' as a parameter and adds 'a' to the L-list, and then returns L with the value [1,2,3 , 'a'].
and this list is assigned to the L2 variable.
source to share