List and it's references in Python -
this question has answer here:
- how clone or copy list? 14 answers
i going through python doc when came upon lists , confused these :-
1.
>>> = [1, 2, 3] >>> b = >>> a.append(4) >>> [1,2,3,4] >>>b [1,2,3,4] >>> = [] >>> print(a) [] >>> print(b) [1, 2, 3, 4] how can appending a change both a , b using a=[] changes a , not b.
- as know
id(a) != id(a[:])why doinga[:]=[]changes a?
thank you.
references variables point objects in memory. doing
b = is making b point same memory location a pointing.
this means through both variables b , a can modify same contents in memory, , explains "why modifying b modifies a".
now, when
a = [] you creataing new empty list in memory , making a pointing it...
of course general explanation, think gives intuition.
Comments
Post a Comment