Create a vector length n with n entries 'x'

Question:

Example:

n = 5
x = 3.5
Output:
array([3.5, 3.5, 3.5, 3.5, 3.5])

My code:

import numpy as np
def init_all_x(n, x):
    np.all = [x]*n
    return np.all
init_all_x(5, 3.5)

My question:

Why init_all_x(5, 3.5).shape cannot run?

If my code is wrong, what is the correct code?
Thank you!

Asked By: Phung Doan

||

Answers:

you can use np.ones

arr = np.ones(5)*3.5
Answered By: Maen

Simple approach with numpy.repeat:

n = 5
x = 3.5
a = np.repeat(x, n)

Output:

array([3.5, 3.5, 3.5, 3.5, 3.5])
Answered By: mozway

For your requirement, no need to use Numpy lib, you can code like this:

def init_all_x(n, x):
    return [x]*n

p = init_all_x(5, 3.5)
print(p)

Output:

[3.5, 3.5, 3.5, 3.5, 3.5]
Answered By: Mansour Torabi

Numpy has a dedicated function np.full to do just this:

n = 5
x = 3.5

out = np.full(n, x)
# array([3.5, 3.5, 3.5, 3.5, 3.5])
Answered By: Chrysophylaxs