3 Easy Ways to Initialize a Python Array

In programming, arrays are a fundamental data structure and are crucial for manipulating and analyzing data. The Python language provides several methods for creating arrays, each method has its own advantages and drawbacks.

In this tutorial, we will explore three different ways to initialize a Python array using numerous examples:

Method 1: Using Direct Method (Square Brackets)

The following code demonstrates how to initialize/create an array using square bracket:

Code:

array_1 = [52] * 5
array_2 = ['Python'] * 3
print('Integer Array: ', array_1)
print('String Array: ',array_2)
  • The default value is enclosed inside the bracket and multiplied with the integer value to return the array of specific size. The multiplied integer number represents the size of the array.
  • The string is passed inside the bracket and multiplied with an integer to return the string array of a particular size.

Output:

The above output verified that the integer array and string array has been initialized successfully.

Method 2: Using Numpy Module

The below code uses the “numpy.empty()” function of the NumPy module to initialize a Python array:

Code:

import numpy
array_value = numpy.empty(3, dtype=int)
print(array_value)
  • The “numpy.empty()” function accepts two arguments. The first argument accepts the size of the array and the second argument takes the data type of the initialized array.
  • The “numpy.empty()” function returns the array containing random values.

Output:

The array of size “3” has been successfully initialized/created.

Method 3: Using List Comprehension Method

The list comprehension approach can also be utilized along with the “for” loop and “range()” function to initialize an array:

Code:

empty_array=[]
empty_array = [5 for i in range(3)]
print(empty_array)
  • The empty array is initialized and stored in a variable named “empty_array”.
  • The “for loop” creates an array of size “3” by iterating over the range and placing the specific value. 
  • The array size is created using the “range()” function.

Output:

The array of size “3” has been created successfully. 

Conclusion

In Python, the square brackets[], np.empty() function, and list comprehension method are used to initialize or create an array. The array of specific sizes is initialized/created using the square bracket approach which is simple and straightforward. We can initialize an array of particular sizes of random values using the “np.empty()” function. This blog presented various ways to initialize a Python array using numerous examples.