A bug?

Rustom Mody rustompmody at gmail.com
Tue Oct 28 02:12:17 CET 2014


On Tuesday, October 28, 2014 6:07:14 AM UTC+5:30, Denis McMahon wrote:
> On Mon, 27 Oct 2014 09:01:57 -0700, umatrp wrote:
> > I use python 3.4.0 version. In the course of developing / running a
> > python program, I have encountered a problem. I have reproduced below a
> > simple program to bring it out.
> >>>> d = [[0]*3]*4 dd = [1,2,3,4,5,6,7,8,9,10,11,12]
> >>>> for i in range(4):
> > ...   for j in range(3): d[i][j] = dd[i*3+j]
> > ...
> >>>> d
> > [[10, 11, 12], [10, 11, 12], [10, 11, 12], [10, 11, 12]]
> > d is not transferred to dd as expected?
> > Of course I can use 'append' & do my job (less elegantly though).
> Not sure if this is elegant or not:
> d = [[list(range(1,13))[i*3+j] for j in range(3)] for i in range(4)]
> but it seems to be a one-line solution for what you're trying to do.

Neat

More generally for d being a 2-D reshape of dd (which may be anything
as long as the size matches)

>>> dd = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d=[[dd[i*3+j] for j in range(3)] for i in range(4)]
>>> d
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]



More information about the Python-list mailing list