Function editing lists in Python -
this question has answer here:
- how pass variable reference? 22 answers
so i've observed in python3 if like
a = 5 def addfive(x): x+=5 return x print(addfive(a),a)
the output "10 5" since not changed function. same not happen lists:
a = [1,2,3] def b(x): z = x z.append(10) b(a) print(a)
when run function changes actual list.
now question: why happen, can read more this(honestly have no idea how word google search) , how can avoid this. please feel free redirect me other articles common problem couldn't find similar.
thanks in advance :)
use copy
module.
import copy = [1,2,3] def b(x): z = copy.deepcopy(x) z.append(10) return z b(a) print(a)
this prints
[1, 2, 3, 10] [1, 2, 3]
Comments
Post a Comment