Declare an empty array in Python
Hello friends, in this tutorial I will tell you how you can initialize an empty array in Python.
I will cover three ways of doing so :
- Initialization using Python
- Initialization using Numpy
- Initialization using itertools
Initialize an empty array in Python
1. Initialize using Python
In this example, I have taken a temporary variable, arr. This variable holds a list of 20 zeroes, you can change the number to your likeliness.
Code :
arr = [0] * 20
Output :
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2. Initialize using Numpy
To use the Numpy library, you must install it and import it into your code. You can check out our tutorial on Array creation in Numpy . I have used the empty()
function. It takes a number as input which defines the length of the empty array. The other attribute is dtype, which I have defined as an object.
Code :
import numpy num = 10 arr = numpy.empty(num, dtype = object)
Output :
[None None None None None None None None None None]
3. Intialize using itertools
itertools is a Python built-in library. After importing the library, I have used the repeat()
function that enables an iterator to do a single job a number of times. In this example, I have given 0 and 10 as arguments for the repeat()
function because I want to repeat 0, 10 times. I have also typecasted the iterator.repeat()
function as a list to return an empty array.
Code :
import itertools arr = list(itertools.repeat(0, 10))
Output :
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Thus you can now declare an empty array in Python.
Leave a Reply