In this article, we will see a different ways to initialize an array in Python.
Table of Contents
Array is collection of elements of same type. In Python, we can use Python list to represent an array.
Using for loop, range() function and append() method of list
Let’s see different ways to initiaze arrays
Intialize empty array
You can use square brackets []
to create empty array.
1 2 3 4 5 6 |
# empty array arr = [] print('Empty array: ', arr) |
Intialize array with default values
Here, we are adding 0 as a default value into the list for n number of times using append() method of list. for looping each time we are using for loop with range() function.
Below is the Python code given:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# number of elements n = 10 # empty array arr = [] defaultValue = 0 # loop for i in range(n) : # add element arr.append(defaultValue) print(arr) |
Here range()
function is used to generate sequence of numbers. We are using range(stop)
to generate list of numbers from 0
to stop
.
Output:
Intialize array with values
You can include elements separated by comma in square brackets []
to initialize array with values.
1 2 3 4 |
arr = [10, 20, 30, 40] print(arr) |
Using list-comprehension
Here, list-comprehension is used to create a new list of n size with 0 as a default value.
Below is the Python code given:
1 2 3 4 5 6 7 8 9 10 11 |
# number of elements n = 10 defaultValue = 0 # make a array of n elements arr = [ defaultValue for i in range(n)] print(arr) |
Output:
Using product (*) operator
Here, product operator (*) is used to create a list of n size with 0 as a default value.
Below is the Python code given:
1 2 3 4 5 6 7 8 9 10 11 |
# number of elements n = 10 defaultValue = 0 # array of n elements arr = [defaultValue] * n print(arr) |
Output:
Using empty() method of numpy module
here, empty() method of numpy is used to create a numpy array of given size with default value None.
Below is the Python code given:
1 2 3 4 5 6 7 8 9 10 11 12 |
# import numpy module import numpy # number of elements n = 10 # array of n elements arr = numpy.empty(n, dtype = object) print(arr) |
Output:
That’s all about how to initialize array in Python.