1

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.

2
  • 1
    Your code will raise a TypeError. I am not sure what you are trying to achieve, can you try rephrasing the question or providing a valid code example? Commented May 24, 2012 at 15:35
  • hi maybe you express has some error, x=x/2, how a list can divide by a integer Commented May 24, 2012 at 15:37

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.