Wael
Wael

Reputation: 87

Initialize and Populate 2 Dimensional Array in Python from other Lists

I want to create 2 dimensional array and populate it with the following information.

n = 7  
j = [0, 1, 2, 3, 4, 5, 6]  
k = [0, 2, 4, 3, 3, 2, 1]  
l = [0 , 46, 52, 30, 36 ,56, 40]  

so, the the first list of the List L should b [0,0,0], second list of list L should be [1,2,46], third should of List L should be the list [2, 4, 52] and so on. But its not working and it keep overriding the values

#!/usr/bin/python3.6

from operator import itemgetter

n = 7
j = [0, 1, 2, 3, 4, 5, 6]
k = [0, 2, 4, 3, 3, 2, 1]
l = [0 , 46, 52, 30, 36 ,56, 40]

L =  [[0]*3]*n

print(L)

x = 0
y = 0
z = 0

while x < len(j):
  L[x][0] = j[x]
  x =  x + 1

while y < len(k):
  L[y][1] = k[y]
  y  = y + 1

while z < len(l):
  L[z][2] = l[z]
  z  = z + 1


print (L)

The current output is
Initialization of L, and thats ok
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

And L after modification, which is very wrong
[[6, 1, 40], [6, 1, 40], [6, 1, 40], [6, 1, 40], [6, 1, 40], [6, 1, 40], [6, 1, 40]]

Upvotes: 0

Views: 60

Answers (1)

iz_
iz_

Reputation: 16593

First and foremost:

L = [[0]*3]*n

is the wrong way to initialize a 2D list. If I set l[0][0] to 1, look what happens:

n = 7
L = [[0]*3]*n
L[0][0] = 1
print(L)

Output:

[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]

To properly initialize a 2D list, do:

L = [[0] * 3 for _ in range(n)]

If you change it to this, your code will work.

But actually, your problem can be solved in a much simpler way. Just use zip:

j = [0, 1, 2, 3, 4, 5, 6]  
k = [0, 2, 4, 3, 3, 2, 1]  
l = [0, 46, 52, 30, 36, 56, 40]

result = [list(x) for x in zip(j, k, l)]
print(result)

Output:

[[0, 0, 0],
 [1, 2, 46],
 [2, 4, 52],
 [3, 3, 30],
 [4, 3, 36],
 [5, 2, 56],
 [6, 1, 40]]

Upvotes: 1

Related Questions