Python – Initialize empty array of given length

Prerequisite: List in Python

As we know Array is a collection of items stored at contiguous memory locations. In Python, List (Dynamic Array) can be treated as Array. In this article, we will learn how to initialize an empty array of some given size.

Let’s see different Pythonic ways to do this task.

Method 1 –

Syntax:



list1 = [0] * size
list2 = [None] * size
filter_none

edit
close

play_arrow

link
brightness_4
code

# initializes all the 10 spaces with 0’s
a = [0] * 10 
  
# initializes all the 10 spaces with None
b = [None] * 10 
  
# initializes all the 10 spaces with A's
c = ['A'] * 5 
  
# empty list which is not null, it's just empty.
d = [] 
  
print (a, "\n", b, "\n", c, "\n", d);

chevron_right


Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 
[None, None, None, None, None, None, None, None, None, None] 
['A', 'A', 'A', 'A', 'A'] 
[]

 
Method 2 – Use loops just like C and assign the size.

Syntax:

a = [0 for x in range(size)] #using loops
filter_none

edit
close

play_arrow

link
brightness_4
code

a = []
b = []
  
# initialize the spaces with 0’s with 
# the help of list comprehensions
a = [0 for x in range(10)]
print(a)
  
# initialize multi-array 
b = [ [ None for y in range( 2 ) ]
             for x in range( 2 ) ]
               
print(b)

chevron_right


Output:

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

[[None, None], [None, None]]

 
Method 3 – Using Numpy to create empty array.

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output:

[None None None None None]

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.