3

I would like to create an array like the following:

# 0 | 4 | 8 | 16 | 32

In which, each element except the first, is the double of the previous one. I can create this smaller through an iteration and so on.

However, as Python provides a lot of one-liner functions, I was wondering if there is one that allows me to do that.

3 Answers 3

6

Could be one line, but this is more explicit:

x = np.multiply.accumulate( np.ones( 10 )*2)
x[0] = 0

OR

x  = 2**np.arange(1,10)
x[0] = 0
Sign up to request clarification or add additional context in comments.

2 Comments

I like the use of arange and exponentiation, makes it clear what's happening.
Or more compactly: np.cumprod(np.full((5,),2))
2

You can use numpy.logspace to get log-spaced ranges. Use the base=N keyword argument to set the base of the exponent:

In [27]: np.logspace(0, 10, 11, base=2).astype(int)
Out[27]: array([   1,    2,    4,    8,   16,   32,   64,  128,  256,  512, 1024])

I like this method because the "logspace" function name makes it clear that I'm going for a range with log (as opposed to linear) spacing.

Comments

2
import numpy as np

You could use a list comprehension to evaluate your power function (2^n in this case), then generate a numpy.array from that.

>>> np.array([0] + [2**i for i in range(2, 10)])
array([  0,   4,   8,  16,  32,  64, 128, 256, 512])

1 Comment

A little explanation would be nice!

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.