[docs] [issue23406] interning and list comprehension leads to unexpected behavior
Abraham Smith
report at bugs.python.org
Sat Feb 7 13:55:26 CET 2015
New submission from Abraham Smith:
Some students were working on matrix routines for practice.
The following code:
>>> L = [ [0]*3 ]*3
>>> for i in range(3):
... for j in range(3):
... if i==j: L[i][j]=1
was expected to return
[[1,0,0],[0,1,0],[0,0,1]]
but it returned
[[1,1,1],[1,1,1],[1,1,1]]
because the list [0]*3 was being interned silently, so all three rows were the same memory!
To see this, I did
>>> map(id, L)
[139634871681464, 139634871681464, 139634871681464]
On the other hand
>>> M=[ [ 0 for i in range(3) ] for j in range(3) ]
does not intern:
>>> map(id, L)
[139634871631672, 139634871681608, 139634871681680]
so the above loop works as expected.
This is true in both python 2.7 and 3.4.
This is very confusing to users!
If this intern behavior with [0]*3 is intended, it should be documented more clearly, because this is something that new students of python might encounter right away when playing with the language's list methods. I didn't see any reference to interning in the discussion of lists in the standard library reference.
Moreover, I also could not find any reference to the automatic interning of mutable objects, such as lists. Personally, I cannot see any reason to silently and automatically intern a mutable object; however, if this behavior is really desired, it should be documented.
----------
assignee: docs at python
components: Documentation
messages: 235520
nosy: Abraham.Smith, docs at python
priority: normal
severity: normal
status: open
title: interning and list comprehension leads to unexpected behavior
versions: Python 2.7, Python 3.4
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue23406>
_______________________________________
More information about the docs
mailing list