Usually when creating certain sequences of numbers, python and numpy offer some syntactic sugar to do so in a simple way, without generating them yourself with for-loops, e.g. range(start, stop, step)
.
I'm having a rather simple problem that I'm struggling to solve in an elegant way: Generate a list of the powers of two. E.g. list = [1, 2, 4, 8, ...]
.
I came up with
n_powers = 4
list = np.zeros(n_powers)
for i in range(0, n_powers):
list[i] = 2 ** i
Is there a better way to do this?
To create a NumPy array, you can use the function np. array() . All you need to do to create a simple array is pass a list to it. If you choose to, you can also specify the type of data in your list.
2D array are also called as Matrices which can be represented as collection of rows and columns. In this article, we have explored 2D array in Numpy in Python. NumPy is a library in python adding support for large multidimensional arrays and matrices along with high level mathematical functions to operate these arrays.
The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.
You seem to be using NumPy, so why not just do this -
>>> 2 ** np.arange(4)
array([1, 2, 4, 8])
This is broadcasted exponentiation.
Maybe just:
l = [2**i for i in range(n)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With