[Python] How do element assignements work with numpy arrays using an array for indexing?

Discussão em 'Python' iniciado por Stack, Julho 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm very puzzled by the following behaviour of numpy when assigning elements to an array using an array as indices. Here is a minimal working example:

    import numpy as np

    i = np.arange(2,4)
    a = np.arange(5)
    a[:] = 0 # this modifies the a array
    print(a)

    b = np.arange(5)
    b[:] = 0 # this does NOT modify the b array
    print(b)


    Why is the a array modified and not the b array? I suspect we are modifying a copy of the b array, but I'm not sure how to show this explicitly. For example, id(a) and id(a[:]) yield different results, yet a is modified.

    Continue reading...

Compartilhe esta Página