简体   繁体   中英

Why doesn't list change?

In Python:

    b = []
    a = np.arange(2)
    b.append(a)
    a = np.arange(4)
    b.append(a)
    print(b) # gives [array([0, 1]), array([0, 1, 2, 3])]

Why doesn't it give [array([0, 1, 2, 3]), array([0, 1, 2, 3])] ?

There are a ton of questions going the other way (to make sure the list does not change -- see here or this explanation on referencing and values ).

From the links above I would expect b[0] == b[1] because I updated a , but this is not the case. What am I missing?

a = np.arange(4) doesn't update the values inside a , it reassigns the reference to a new array. This is reflected in b , as it has two different arrays as elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM