Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a NumPy array with powers of 2

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?

like image 552
Honeybear Avatar asked Mar 09 '18 18:03

Honeybear


People also ask

How do you make a 2D NumPy array?

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.

What is a 2D NumPy array?

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.

How can you create a NumPy array?

The array object in NumPy is called ndarray . We can create a NumPy ndarray object by using the array() function.


2 Answers

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.

like image 180
cs95 Avatar answered Sep 19 '22 06:09

cs95


Maybe just:

l = [2**i for i in range(n)]
like image 33
Ivan Velichko Avatar answered Sep 20 '22 06:09

Ivan Velichko