Skip to content Skip to sidebar Skip to footer

Python -- By Value Vs By Reference

Until recently, I thought Python passed parameters by value. For example, def method1(n): n = 5 return n n = 1 m = method1(n) >>> n == 5 >>> False But if

Solution 1:

Python always passes by assignment , even in the first case, actually the object reference is passed. But when you do an assignment inside the function, you are causing the name to refer a new object. That would not mutate the name/variable that was used to pass the value to the function (Better explained in the below example).

Example -

>>>deffunc(n):...    n = [1,2,3,4]...return n...>>>l = [1,2,3]>>>func(l)
[1, 2, 3, 4]
>>>l
[1, 2, 3]

In your case, when you do del list[0] you are actually mutating the list in place (deleting the first element from it) , and hence it reflects in the place where the function was called from as well.

Post a Comment for "Python -- By Value Vs By Reference"