Declare an empty array in Python

In this tutorial, we are going to learn about an array, empty array, and a number of ways to declare it in Python.

Also, we will learn how to check if an array is empty or not. So, Let’s start with basic information about an array.

About array

An array is a collection of values stored inside a single name. Array stores values at contiguous locations and of the same data type. The value in the array can be fetched through the index.

Here, you might have got a basic idea about the array. Now we need to understand what is an empty array in Python.

Empty array

An empty array is an array that has no value or is null. We can use the empty array later to append the values or modify them.

Ways to create an empty array in Python

The very first way is to execute the following line of code to create an empty array.

myarr = []

This will create an empty array. Now, we can append values to it as.

myarr.append(5)
myarr.append(9)

OUTPUT
[5,9]
The second way to declare an empty array in Python is by creating a list and multiplying it by the number(length of the array) to create an empty array.

myarr = [0]*4
print(myarr)

This will create an empty array of size 4. print(myarr) will result in the following output.

OUTPUT
[0, 0, 0]

Now we will create the empty array in Python using for loop as

myarr = [0 for a in range(4)]
print(myarr)

This also creates an empty array in Python and its output looks like

OUTPUT
[0, 0, 0]

Additionally, we can create an empty array using NumPy. So, install and import NumPy then execute the following code.

myarr = numpy.empty(5, dtype=object)
print(myarr)
OUTPUT
[None None None None None]

How to check an array is empty or not?

myarr=[]
if not myarr:
print("My array is empty")
OUTPUT
My array is empty

Here is another example:

Array2 = [None] * 21
print(Array2)

Output : [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None]

So, here tutorial on how to declare an empty array in Python ends. Hope you enjoyed learning this topic. Feel free to share your reviews and comment.

Leave a Reply

Your email address will not be published.