How to initialize array in Python

In this article, we will see a different ways to initialize an array in Python.

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.

Empty array: []

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:

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:

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

Intialize array with values

You can include elements separated by comma in square brackets [] to initialize array with values.

[10, 20, 30, 40]

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:

Output:

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

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:

Output:

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

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:

Output:

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

That’s all about how to initialize array in Python.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *