0
l1 = [4, 8, 12,16,3,7,11,15,2,6,10,14,1,5,9,13]

output :

[4,8,12,16]
[3,7,5,11]
[1,6,10,14]
[1,5,9,13]

m =4
n=4
tmp = [[0]*m]*n
a = 0
for i in range(m):
    for j in range(n):
       tmp[i][j] = l1[a]
       a += 1

not printing in required format. What's wrong here ? Can you please help me.

Fresher
  • 97
  • 2
  • 7
  • Does this answer your question? [Read flat list into multidimensional array/matrix in python](https://stackoverflow.com/questions/3636344/read-flat-list-into-multidimensional-array-matrix-in-python) and https://stackoverflow.com/questions/6614261/how-can-i-turn-a-flat-list-into-a-2d-array-in-python – Tomerikoo Oct 22 '20 at 13:20

4 Answers4

0

You could achieve this with the following list of comprehension:

list1 = [4, 8, 12,16,3,7,11,15,2,6,10,14,1,5,9,13]
[list1[x:x+4] for x in list(range(0,len(list1),4))]

Output

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

Sebastien D
  • 4,369
  • 4
  • 18
  • 46
0

Iterate through the initial list with step of m and every time append list of m elements to the final list where m is number of elements in each row.

t = []
for i in range(0, len(l1), m):
    t.append(l1[i:i+m])
print(t)
pradeexsu
  • 1,029
  • 1
  • 10
  • 27
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality – Fabio Veronese Oct 22 '20 at 13:50
0

The issue with the code is the array initialization part. tmp = [[0]*m]*n This will create a common memory address and whatever changes you are making to one index will be reflected to other index as well.

So to initialize the list you can use the following code

tmp = [[0 for _ in range(m)] for _ in range(n)]

The simple method is already shared by @Sebastien D

Aji CS
  • 13
  • 3
0

You just need to change the way you initialize your tmp matrix

tmp = [[[0] for _ in range(m)] for _ in range(n)]
S.Patole
  • 47
  • 1
  • 8