Initialize a Python Array – 3 Methods

Python Array:

Init array python: An array in Python is a data structure that stores similar data items in contiguous memory locations.

When compared to a List which is a dynamic Array, Python Arrays keeps elements of the same datatype. A Python List, on the other hand, can store entries of several/different data types.

There are various ways to initialize an array in Python. They are:

  • Using for loop and range() Function
  • Using Numpy Module
  • Using Direct Method

1)Using for loop and range() Function

Initialize an array in python: The Python for loop and range() functions can be used together to initialize an array with a default value.

Syntax:

[value for element in range(number)]

The range() method in Python takes a number as an argument and produces a sequence of numbers that begins at 0 and ends at the supplied number, incrementing by one each time.

Python’s for loop would assign 0 (default value) to each element in the array that fell within the range set by the range() method.

Example

# Create an empty array and store it in a variable
gvn_arry = []
gvn_arry = [3 for itr in range(4)]
# Print the given array
print("The given array = ", gvn_arry)

Output:

The given array =  [3, 3, 3, 3]

2)Using Numpy Module

Initialize python array: The Python NumPy module may be used to effectively construct arrays and manipulate the data contained within them. The numpy.empty() function returns an array of a given size with the value ‘None’ as the default.

Syntax:

numpy.empty(size, dtype=object)

Example

# Import numpy module using the import keyword
import numpy
# Pass some random size of array and dtype=object as an argument to the numpy.empty()
# function to create an array.
gvn_arry = numpy.empty(6, dtype=object)
# Print the given array
print("The given array = ", gvn_arry)

Output:

The given array = [None None None None None None]

Creating a multi-dimensional Array(matrix):

# Import numpy module using the import keyword
import numpy
# Pass rowsize, columnsize as arguments to the shape function to create a
# multi-dimensional array.
gvn_matrx = numpy.empty(shape=(3, 3), dtype='object')
# Print the given multi-dimensional array.
print("The Given multi-dimensional array(i.e, matrix) = \n", gvn_matrx)

Output:

The Given multi-dimensional array(i.e, matrix) = 
[[None None None] 
 [None None None] 
 [None None None]]

3)Using Direct Method

Python init array: We can use the following command to initialize the data values when declaring the array:

Syntax:

array_name = [default-value]*size

Example

gvn_arry = [1] * 5
# Print the given number array.
print(gvn_arry)

gvn_strngarry = ['btechgeeks'] * 4
# Print the given string array.
print(gvn_strngarry)

Output:

[1, 1, 1, 1, 1]
['btechgeeks', 'btechgeeks', 'btechgeeks', 'btechgeeks']