How to create an array with the same value in Python

You can create an array with the same value in Python with any of the following methods. If you want to learn Python, I highly recommend reading This Book.

Method 1: Using np.repeat()

# Import the NumPy library as np
import numpy as np

# Create an array with the same number 2 
a = np.repeat(2, 5)

# Display the array
print(a)

Output:

[2 2 2 2 2]

Method 2: Using np.full()

# Import the NumPy library as np
import numpy as np

# Create an array with the same number 2 
a = np.full((4, 6), 2, dtype=int)

# Display the array
print(a)

Output:

[[2 2 2 2 2 2]
 [2 2 2 2 2 2]
 [2 2 2 2 2 2]
 [2 2 2 2 2 2]]

Method 3: Using array.fill()

# Import the NumPy library as np
import numpy as np

# Create an empty array
a = np.empty(10)

# Fill the array with the same number 2
a.fill(2)

# Display the array
print(a)

Output:

[2. 2. 2. 2. 2. 2. 2. 2. 2. 2.]

Free Learning Resources

Leave a Comment

Your email address will not be published.