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?
listis not alistit is anumpy.ndarray. These are two different data-structures that typically have different idiomatic approaches to doing things. If yourlistvariable were indeed alistobject, this would be a perfectly reasonable way of doing it, except you would normally use.appendon an empty list, and not pre-allocate it.listas a variable name because your overwrite the built-in typelistthen.