Multi-dimensional list initialization

wxjmfauth at gmail.com wxjmfauth at gmail.com
Mon Nov 5 10:55:45 CET 2012


Le lundi 5 novembre 2012 07:28:00 UTC+1, Demian Brecht a écrit :
> So, here I was thinking "oh, this is a nice, easy way to initialize a 4D matrix" (running 2.7.3, non-core libs not allowed):
> 
> 
> 
> m = [[None] * 4] * 4
> 
> 
> 
> The way to get what I was after was:
> 
> 
> 
> m = [[None] * 4, [None] * 4, [None] * 4, [None * 4]] 
> 
> 
> 
> (Obviously, I could have just hardcoded the initialization, but I'm too lazy to type all that out ;))
> 
> 
> 
> The behaviour I encountered seems a little contradictory to me. [None] * 4 creates four distinct elements in a single array while [[None] * 4] * 4 creates one distinct array of four distinct elements, with three references to it:
> 
> 
> 
> >>> a = [None] * 4
> 
> >>> a[0] = 'a'
> 
> >>> a
> 
> ['a', None, None, None]
> 
> 
> 
> >>> m = [[None] * 4] * 4
> 
> >>> m[0][0] = 'm'
> 
> >>> m
> 
> [['m', None, None, None], ['m', None, None, None], ['m', None, None, None], ['m', None, None, None]]
> 
> 
> 
> Is this expected behaviour and if so, why? In my mind either result makes sense, but the inconsistency is what throws me off.
> 
> 
> 
> Demian Brecht
> 
> @demianbrecht
> 
> http://demianbrecht.github.com

----------

You probably mean a two-dimensional matrix not a 4D matrix.

>>> def DefMatrix(nrow, ncol, val):
...     return [[val] * ncol for i in range(nrow)]
...     
>>> aa = DefMatrix(2, 3, 1.0)
>>> aa
>>> aa = DefMatrix(2, 3, 1.0)
>>> aa
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
>>> aa[0][0] = 3.14
>>> aa[1][2] = 2.718
>>> aa
[[3.14, 1.0, 1.0], [1.0, 1.0, 2.718]]
>>> 
>>> bb = DefMatrix(2, 3, None)
>>> bb
[[None, None, None], [None, None, None]]
>>> bb[0][0] = 3.14
>>> bb[1][2] = 2.718
>>> bb
[[3.14, None, None], [None, None, 2.718]]


jmf



More information about the Python-list mailing list