Types inside a function in Python. Why some gets updated but not others? -
this question has answer here:
- immutable vs mutable types 14 answers
why calling several times in row following function:
a = [] def test(a,b): if b > 0: a.append(1) return
with test(a,4), enlarges list each time, calling several times in row function:
a = 0 def test(a,b): if b > 0: += 1 return
with test(a,4) returns 1 every single time instead of 1, 2, 3, etc.?
it looks lists updated function , retain updated value after function finished execute, while behavior doesn't hold integers (and guess floats , several other types).
integers immutable; lists mutable. a += 1
changes value of a
reassigning value refers to. a.append(1)
adds value 1
list a
refers to, without changing reference itself.
in test
function, a
if reference within function's scope; not same reference a
in global scope. however, when passing mutable object, reference remains same; allowing object modified without need reassign variable. in function
def test(a, b): if b > 0: += 1 return
the value of a
modified relative test
. reassign value globally, need perform action in global scope (or use global
keyword). so, instead of test(a, 4)
, use a = test(a, 4)
reassign value of a
.
Comments
Post a Comment