Basic List operation
Question:
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?
Answers:
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
Because list.append
returns None
, you are calling id(None)
, which there will only be one instance of.
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?
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
Because list.append
returns None
, you are calling id(None)
, which there will only be one instance of.