+ 1
please explain the lost output | python
def chval(x): x*=3 print(x) x=3 chval(x) print(x) x=[1,2] chval(x) print(x) Code output: 9 3 [1,2,1,2,1,2] [1,2,1,2,1,2] the lost out-put was little confusing some one please explain that please
2 Réponses
+ 1
list is a mutable type. Mutable types behave as if they are passed by reference while immutable types behave as if they are passed value.
More info:
https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-pass-by-reference/
Check the id's of the objects. Also, note I changed the local variables name the y in the function.
def chval(y):
y*=3
print("id: y", id(y))
print(y)
x=3
chval(x)
print("id: x", id(x))
print(x)
x=[1,2]
chval(x)
print("id: x", id(x))
print(x)
+ 1
Take a look at function body
x *= 3
print(x)
What happens to <x> in the `chval` function is contextual. Meaning, what happens to <x> when <x> was an `int` will be different to that when <x> was a `list`.
When <x> was an `int`, its value will be multiplied by 3. Now remember, `int` is an immutable type (class), meaning, the modification to `int` <x> in function `chval` will not reflect to the actual object outside the `chval` function.
When <x> was a `list`, the function will replicate the `list` contents three times. This is why [1, 2] becomes [1, 2, 1, 2, 1, 2]. And also remember that `list` is a mutable type (class), meaning, the changes written to the `list` will reflect to the actual object outside the `chval` function.