# 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?

+3

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!

0

source

`f2`

adds the second argument to the list passed as the first argument. Adding `"a"`

in `[1, 2, 3]`

will result in the output `[1, 2, 3, "a"]`

you see.

0

source

If you want to get L1 as [1,2,3], assign a new list to it ...

``````def f2(L,x):
L3 = L.copy()  # copy passed list 'L' to L3
L3.append(x)
return L3 # return list with x at end of list
```

```

But it won't change your current L1 list

0

source

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.

0

source

All Articles