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?

Asked By: fsociety

||

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
Answered By: Martijn Pieters

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

Answered By: iobender
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.