3 ways to initialize a Python Array

3 Ways To Initialize A Python Array

Hey, folks! In this article, we will be focusing on some Easy Ways to Initialize a Python Array.


What is a Python array?

Python Array is a data structure that holds similar data values at contiguous memory locations.

When compared to a List(dynamic Arrays), Python Arrays stores the similar type of elements in it. While a Python List can store elements belonging to different data types in it.

Now, let us look at the different ways to initialize an array in Python.


Method 1: Using for loop and Python range() function

Python for loop and range() function together can be used to initialize an array with a default value.

Syntax:

[value for element in range(num)]

Python range() function accepts a number as argument and returns a sequence of numbers which starts from 0 and ends by the specified number, incrementing by 1 each time.

Python for loop would place 0(default-value) for every element in the array between the range specified in the range() function.

Example:

arr=[]
arr = [0 for i in range(5)] 
print(arr)

We have created an array — ‘arr’ and initalized it with 5 elements carrying a default value (0).

Output:

[0, 0, 0, 0, 0]

Method 2: Python NumPy module to create and initialize array

Python NumPy module can be used to create arrays and manipulate the data in it efficiently. The numpy.empty() function creates an array of a specified size with a default value = ‘None’.

Syntax:

numpy.empty(size,dtype=object)

Example:

import numpy as np
arr = np.empty(10, dtype=object) 
print(arr)

Output:

[None None None None None None None None None None]

Method 3: Direct method to initialize a Python array

While declaring the array, we can initialize the data values using the below command:

array-name = [default-value]*size

Example:

arr_num = [0] * 5
print(arr_num)

arr_str = ['P'] * 10
print(arr_str)

As seen in the above example, we have created two arrays with the default values as ‘0’ and ‘P’ along with the specified size with it.

Output:

[0, 0, 0, 0, 0]
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P']

Conclusion

By this, we have come to the end of this topic. Please feel free to comment below in case, you come across any doubt.


References