Understanding python arrays

I have issues understanding how Arrays work in python.

I wrote this short demo code:

from numpy import zeros

a = zeros((3), 'd')
b = zeros((2,3), 'd')
for i in range(2):
    for j in range(3):
        a[j] = i*j
    b[i] = a
print "A: " + str(a) + "\n"
print "B: " + str(b)

The Output of this is:

A: [ 0.  1.  2.]
B: [[ 0.  0.  0.] [ 0.  1.  2.]]

So here is my question. Why isn't the output for this:

A: [ 0.  1.  2.]
B: [[ 0.  1.  2.] [ 0.  1.  2.]]

Because I made the changes in the same a and the address of the array hasn't changed.

Upvotes: 0

Views: 139

Answers (3)

asongtoruin
asongtoruin

Reputation: 10369

Arrays do not exhibit the behaviour you are expecting, however Lists will. See the following example:

import numpy as np

a = np.zeros(3, 'd')
b = np.zeros(3, 'd')
c = np.zeros((2,3), 'd')

c[0] = a
c[1] = b

a[1] = 2
b[0] = 1

print 'Matrix A: {}'.format(a)
print 'Matrix B: {}'.format(b)
print 'Matrix C: {}'.format(c)

a = [0, 0, 0]
b = [0, 0, 0]
c = [a, b]

a[1] = 2
b[0] = 1

print 'List A: {}'.format(a)
print 'List B: {}'.format(b)
print 'List C: {}'.format(c)

When we use matrices, c[0] copies the current value of a, c[1] does the same for b. The references are lost, so modifications to a and b have no effect on c. Hence, we print:

Matrix A: [ 0.  2.  0.]
Matrix B: [ 1.  0.  0.]
Matrix C: [[ 0.  0.  0.]
 [ 0.  0.  0.]]

However for lists, the references are retained. Hence, we print:

List A: [0, 2, 0]
List B: [1, 0, 0]
List C: [[0, 2, 0], [1, 0, 0]]

Upvotes: 0

Paul Panzer
Paul Panzer

Reputation: 53109

You appear to be assuming that

b[i] = a

inserts a reference to a into b. That is not the case. Assignment to an array slice copies the data. This behaviour is similar to slice assignment with lists.

Maybe the confusion comes from it being different the other way round?

a = b[i]

does not copy, it creates a view; this is different to list slicing.

Upvotes: 1

Christian Frei
Christian Frei

Reputation: 481

Its [ 0. 0. 0.] because:

the first loops start with "0" so you have for "i" the zero:

a[j] = 0*j

everything multiplied with 0 is zero.

Upvotes: 0

Related Questions