Reputation: 2680
How can i express this construct in a more efficient way?
x = [2, 4, 6, 8, 10]
for p in x:
x = x/2
print x
there has to be a good way to do this.
Upvotes: 1
Views: 74
Reputation: 500367
If you are trying to divide every element of x
by 2
, then the following will do it:
x = np.array([2, 4, 6, 8, 10])
x /= 2
The resulting value of x
is array([1, 2, 3, 4, 5])
.
Note that the above uses integer (truncating) division. If you want floating-point division, either make x
into a floating-point array:
x = np.array([2, 4, 6, 8, 10], dtype='float64')
or change the division to:
x = x / 2.0
Upvotes: 3
Reputation: 13477
If it is a numpy array You can do it all at once:
In [4]: from numpy import array
In [5]: x = array([2, 4, 6, 8, 10])
In [6]: print x/2
[1 2 3 4 5]
Upvotes: 0