0

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!

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Phung Doan
  • 25
  • 4
  • Does this answer your question? [NumPy array initialization (fill with identical values)](https://stackoverflow.com/questions/5891410/numpy-array-initialization-fill-with-identical-values) – mkrieger1 Dec 02 '22 at 11:29

4 Answers4

0

you can use np.ones

arr = np.ones(5)*3.5
Maen
  • 725
  • 7
  • 10
0

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])
mozway
  • 194,879
  • 13
  • 39
  • 75
0

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]
Mansour Torabi
  • 411
  • 2
  • 6
0

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])
Chrysophylaxs
  • 5,818
  • 3
  • 10
  • 21