[Numpy-discussion] array shift and |=, copy, and backward operations

Tim Hochberg tim.hochberg at cox.net
Fri Feb 10 12:51:02 EST 2006

Nico wrote:

>a = array([0,1,0,0])
>a[1:] |= a[:-1]
>gives the unexpected result [0 1 1 1] instead of [0 1 1 0] because
>python performs the |= on the forst cell, then on the second, and so on.
>I found two ways to get it right, with a copy:
>b = a.copy()
>a[1:] |= b[:-1]
You could also do:

a[1:] = a[1:] | a[:-1]

This is nearly the same as the copy version, but uses very slightly less 
space and is clearer IMO.

>or working backward:
>a[-1:1:-1] |= a[-2:0:-1]
>which is better, in terms of speed (and memory management), for large 3D
The backwards version will be better in terms of memory usage and almost 
certainly in terms of speed as well since it avoids and extra copy and 
should have better locality of reference (also because of no extra 
copy). It's a little obscure though. I'd be tempted to do something like.

a_rev = a[::-1]
a_rev[:-1] |= a_rev[1:]
# a holds result.

Another question / suggestion is: are you using a[0]. This looks like an 
operation where you may well be throwing away a[0] when you are done 
anyway. If that is the case, would it work to use:

a[:-1] |= a[1:]
a = a[:-1]

This last will give you the same result as the others except that the 
first value will be missing.


More information about the NumPy-Discussion mailing list