0

Assuming I have a the a list of 9 items, I want to convert it into a list of 3 by 3 items

from [1,2,3,4,5,6,7,8,9] -> [[1,2,3],[4,5,6],[7,8,9]]

this is the code:

def main():

    L = range(1,10)
    twoD= [[0]*3]*3     #creates [[0,0,0],[0,0,0],[0,0,0]]

    c = 0
    for i in range(3):
        for j in range(3):
            twoD[i][j] = L[c]

            c+=1

for some reason this returns

twoD = [[7, 8, 9], [7, 8, 9], [7, 8, 9]]

and I have no clue why, what is making it do this?

jean
  • 973
  • 1
  • 11
  • 23
  • Also see http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python – matsjoyce Oct 29 '14 at 17:35
  • Reason: [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists) – Ashwini Chaudhary Oct 29 '14 at 17:36
  • Oh wow, never thought about that! thanks for pointing that out – jean Oct 29 '14 at 17:37

1 Answers1

0

You could use the following list comprehension.

>>> l = [1,2,3,4,5,6,7,8,9]
>>> [l[i:i+3] for i in range(0, len(l), 3)]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

More generally, you could write such a function

def reshape(l, d):
    return [l[i:i+d] for i in range(0, len(l), d)]


>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

>>> reshape(l,3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]

>>> reshape(l,5)
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    this is a great technique, but I want to understand why mine is returning the wrong value? – jean Oct 29 '14 at 17:36
  • Because the way you are generating the inner lists is making copies of the same sublist. See the above linked posts in the comments. – Cory Kramer Oct 29 '14 at 17:39