Performant Python

Solutions

Re-initialise

In [7]:
c = np.zeros( (3,3) )
print("c", c)
print("d", d)
print("e", e)
c [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
d [[10.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
e [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

If we reintialise c, d does not get changed and is still the original array. You can also use the function id to check whether two variables point to the same object:

In [8]:
print(id(c))
print(id(d))
print(id(e))
139972242570496
139972242569536
139972242569936

In [11]:
print(x[2:-3:2])
print(x[::-2])
[2 4]
[7 5 3 1]

Negative indices in the stop, start positions work as they do in referencing individual elements of the array.

A negative stride work backwards through the array, starting by default from the last element.

In [15]:
n = np.ones( (3,3) )
o = n[0]
print("n", n)
print("o", o)
n [[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
o [1. 1. 1.]
In [16]:
n[(0,0)] = 2
print("n", n)
print("o", o)
n [[-1. -1. -1.]
 [ 1.  2.  1.]
 [ 1.  1.  1.]]
o [-1. -1. -1.]
In [17]:
o[:] = -1
print("n", n)
print("o", o)
n [[-1. -1. -1.]
 [ 1.  2.  1.]
 [ 1.  1.  1.]]
o [-1. -1. -1.]

If you want to copy slices, as with whole arrays you need to use <ndarray>.copy().