简体   繁体   中英

For a numpy array, is there a difference between assigning to array and array[:]?

This a quite basic and subtle question that I've never considered before, but I recently stumbled across the notation a[:] again and this time it caught my attention. Consider the two following examples:

Example A

a     = numpy.zeros(10)
vals  = numpy.arange(10)
a     = vals**2

Example B

a     = numpy.zeros(10)
vals  = numpy.arange(10)
a[:]  = vals**2

The difference is solely in the assignment in the last line. For years I've never thought about the difference between the two. But is there a difference? Does B use less memory by directly assigning the values to the existing array vs. creating another temporary array in example A? Or are the two identical after all (even under the hood)?

Yes, the difference is that a = changes the value associated with the name a and a[:] = internally mutates a .

Mutating a[:] internally should take up a little less memory, since the original value of a doesn't need to be separately garbage collected after the assignment (as no names point to it anymore).

This also stands for other Python objects, collections, etc, that support slice assignment (and in fact, the fact the same object is modified has an important use case with filtering directories in os.walk() ).

However, your use case will probably be best served with just

a = numpy.arange(10)  # (or however you'd get the values to square)
a **= 2

since Numpy can optimize the __ipow__ inline power operation to happen all in-place and there would be no additional allocation for vals ** 2 before it's put in its place.

Result of the first:

[ 0  1  4  9 16 25 36 49 64 81]

Result of the second:

[ 0.  1.  4.  9. 16. 25. 36. 49. 64. 81.]

Do those really look identical to you?

Assigning into an existing array keeps its dtype . Assigning just to the variable instead gets you whatever the new value has.

Also, if you had another reference to the original array, ie, let's say you had done b = a , then your first code won't affect b at all while your second code will.

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