On 03/30/2017 04:23 PM, Pavol Lisy wrote:
On 3/30/17, Nick Coghlan <ncogh...@gmail.com> wrote:
On 30 March 2017 at 19:18, Markus Meskanen <markusmeska...@gmail.com>
wrote:
d = [[0] * 5 for _ in range(10)]
d = [[0]*5]*10 # what about this?
These are not quite the same when the repeated object is mutable. Compare:
>>> matrix1 = [[0] * 5 for _ in range(10)]
>>> matrix1[0].append(1)
>>> matrix1
[[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0,
0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> matrix2=[[0]*5]*10
>>> matrix2[0].append(1)
>>> matrix2
[[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0,
0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1]]
so the comprehension is usually necessary.
Wolfgang
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/