How to Initialize Array in Python
Python does not have a built-in array data type. To use an array, you need to import a numpy library, and then you can use the np.array() method to create an array. The array is a data structure that holds similar data values at contiguous memory locations.
Python initialize array
To initialize an array in Python, use the numpy.empty() function. The numpy.empty() function creates an array of a specified size with a default value = “None“.
Syntax of np.empty()
import numpy as np arr = np.empty(8, dtype=object) print(arr)
[None None None None None None None None]
You can see that we have initialized a numpy array with 8 None elements using the empty() function.
Initializing array using for loop and range() method
The for loop and range() function can initialize an array with a default value. The range() function takes a number as an argument and returns a sequence of numbers that starts from 0 and ends by the specified number, incrementing by 1 each time.
In this example, we are creating a list as an array.
[value for item in range(num)]
arr =  arr = [0 for i in range(5)] print(arr)
[0, 0, 0, 0, 0]
The direct method to initialize a Python array
You can use the direct method to initialize a Python array. Use the following code snippet to create an empty Python array.
array_name = [default-value] * size
arr_data =  * 5 print(arr_data) arr_str = ['K'] * 11 print(arr_str)
[0, 0, 0, 0, 0] ['K', 'K', 'K', 'K', 'K', 'K', 'K', 'K', 'K', 'K', 'K']
That’s it for this tutorial.