How to create or initialize an array with same values in Python

In this tutorial, we are going to learn how to create or initialize an array with the same values in Python. It’s very easy and simple. Let’s see how it will work.

The array is a combination of homogeneous elements having the same data type. It’s a collection of blocks having contiguous memory allocation.

For using array in python we have to use array module or we can use arrays from the NumPy library also. Today we are going to use NumPy for declaring arrays. NumPy offers various operations on arrays.

Create an array with the same values using NumPy

# Importing numpy module
import numpy as np

np.full(10, 7)
#This will create array of number 7 repeated 10 times

Output :

array([7, 7, 7, 7, 7, 7, 7, 7, 7, 7])

As you can see using the full() function array of similar elements is created. The full() function takes a parameter size and element respectively. Adding furthermore to it we can create an array of arrays just like a two-dimensional array.

np.full((4, 6), 8)
#This will create array of arrays

Output

array([[8, 8, 8, 8, 8, 8], 
       [8, 8, 8, 8, 8, 8], 
       [8, 8, 8, 8, 8, 8], 
       [8, 8, 8, 8, 8, 8]])

We can give here data type also by using dtype. Here all the elements will be Integer types.

np.full((3, 4), 1, dtype=int)

array([[1, 1, 1, 1], 
       [1, 1, 1, 1], 
       [1, 1, 1, 1]])

There is another method to create an array with the same values. We can use the repeat() function also. Here is a demonstration.

np.repeat(5, 8)
# This will create array of number 5 repeated 8 times

Output

array([5, 5, 5, 5, 5, 5, 5, 5])

In this way, we can create arrays with the same values.

Also read: Python numpy.empty() function

Leave a Reply

Your email address will not be published.