List and it's references in Python -


this question has answer here:

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.

  1. as know id(a) != id(a[:]) why doing a[:]=[] 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

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -