1

I tried a very basic code in the python interactive shell

>>> a=[1,2,3]
>>> id(a)
36194248L
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>> id(a)
36194248L
>>>
>>> id([1,2,3])
36193288L
>>> id([1,2,3].append(4))
506033800L
>>> id([1,2,3].append(5))
506033800L
>>> id([1,2,3].append(6))
506033800L

Q: When i assign a list to a variable named 'a', and try to append more value, the id() does not change but if i try the same thing without assigning to a variable,the id() changes.Since lists are mutable(i.e. allow change at same memory address),why this behaviour is seen?

fsociety
  • 877
  • 2
  • 9
  • 22

2 Answers2

4

list.append() returns None, not the list.

You are getting the id() result for that object, and None is a singleton. It'll always be the same for a given Python interpreter run:

>>> id(None)
4514447768
>>> [].append(1) is None
True
>>> id([].append(1))
4514447768
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
1

Because list.append returns None, you are calling id(None), which there will only be one instance of.

iobender
  • 2,936
  • 1
  • 13
  • 18