Skip to content
Related Articles

Related Articles

Python – Initialize empty array of given length

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 18 Aug, 2022
Improve Article
Save Article

Prerequisite: List in Python 

As we know Array is a collection of items stored at contiguous memory locations. In Python, a List (Dynamic Array) can be treated as an Array. In this article, we will learn how to initialize an empty array of some given size. Let’s see different Pythonic ways to create an empty list in Python with a certain size.

Method 1: Initialize empty array using * Operator

In this example, we are creating different types of empty using an astrick(*) operator.

Python3




# initializes all the 10 spaces with 0’s
a = [0] * 10
print("Creating empty list of zeros: ", a)
 
# initializes all the 10 spaces with None
b = [None] * 8
print("Creating empty list of None: ", b)
 
# initializes all the 10 spaces with A's
c =  [[0] * 4] * 3
print("Creating 2D empty list of zeros: ", c)
 
# empty list which is not null, it's just empty.
d = []
print("Creating empty list of zeros: ", d)

Output:

Creating empty list of zeros:  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Creating empty list of None:  [None, None, None, None, None, None, None, None]
Creating 2D empty list of zeros:  [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Creating empty list of zeros:  []

Method 2:  Create an empty list in python with a certain size using list comprehension

In this example, we are using Python List comprehension for 1D and 2D empty arrays.

Python3




# initialize the spaces with 0’s with
# the help of list comprehensions
a = [0 for x in range(10)]
print(a)
 
b = [[0] * 4 for i in range(3)]
print(b)

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Method 3:  Create an empty list of a specific size in Python using a loop

In this example, we are using a Python loop for 1D and 2D empty arrays.

Python3




b= []
for x in range(5):
    b.append([[]])
           
print(b)
 
c = []
for x in range(5):
    c.append(0)
     
print(c)

Output:

[[[]], [[]], [[]], [[]], [[]]]
[0, 0, 0, 0, 0]

Method 4:  Initialize empty array using Numpy

In this method, we are using the Numpy module to generate an empty matrix of 1D and 2D sizes using np.empty().

Python3




import numpy
 
# create a simple array with numpy empty()
a = numpy.empty(5, dtype=object)
print(a)
 
# create multi-dim array by providing shape
matrix = numpy.empty(shape=(2, 5), dtype='object')
print(matrix)

Output:

[None None None None None]

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!