1

I'm implementing the outer product function between two vectors (cross product), I have encountered something that I don't understand.

The array value assignment doesn't work as I was expecting. in the following code, each time that I assign a value to out[i][j], the value is being assigned to all the out[x][j] (not just where x==i).

Can someone explain what's going on?

def outer_prod(vec_a, vec_b): 
    out=[]
    item=[]
    for i in range(len(vec_b)):
        item.append(0)
    for i in range(len(vec_a)):
        out.append(item)
    print(str(out))    

    for i in range(len(vec_a)):
        for j in range(len(vec_b)):
            out[i][j] = vec_a[i]*vec_b[j]
            print(out)
    return out

outer_prod([1,2,3], [4,5,6])

The output:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[4, 0, 0], [4, 0, 0], [4, 0, 0]]
[[4, 5, 0], [4, 5, 0], [4, 5, 0]]
[[4, 5, 6], [4, 5, 6], [4, 5, 6]]
[[8, 5, 6], [8, 5, 6], [8, 5, 6]]
[[8, 10, 6], [8, 10, 6], [8, 10, 6]]
[[8, 10, 12], [8, 10, 12], [8, 10, 12]]
[[12, 10, 12], [12, 10, 12], [12, 10, 12]]
[[12, 15, 12], [12, 15, 12], [12, 15, 12]]
[[12, 15, 18], [12, 15, 18], [12, 15, 18]]
Ramin Zahedi
  • 455
  • 2
  • 6
  • 20

0 Answers0