How to declare an array in Python?

Rate this post

Have you been wondering – “How to declare an array in Python?” Well, if your answer is yes, then you are at the right place to find your answers; as in this article, we are going to learn about the different ways of declaring an array in Python.

Video Walkthrough

A Quick Introduction to Arrays in Python

In Python, arrays are not built-in data types. Instead, we have lists in Python. An array is similar to a list in many ways but has different properties and declarations. Python provides us with different libraries and modules to play around with arrays and use in our code. Hence, without further delay, let us begin our array journey in Python.😉

What is an array in Python?

An array is a container that can hold a collection of items of the same type. The items stored in an array are called elements, and these elements can be accessed using indexes. Arrays can have one or more axes where each axis is considered as a dimension. You can think of a list as a one-dimensional array.

What are dimensions in an array?

Dimension represents a single level of depth of an array. Simply put, you can think of it as the number of axes an array has.

  • 0D array has a single element. In simple words, each value contained in an array is a 0-D array.
  • 1D arrays consist of a single dimension. In a 1D array, the array will have just one dimension. This means when you add elements or remove elements from a 1d array, it grows or shrinks just vertically. You can use a single index to access the elements of a 1D array.
  • A nested array, i.e., an array that contains another array, is a 2D array; for example – a Matrix (not the movie, though!😂).

To learn more about 2d arrays please refer to this article – “How To Create a Two Dimensional Array in Python?

Note

  • An array consists of homogeneous elements, i.e., all the elements in an array are of the same type, whereas a list can have homogeneous as well as heterogeneous elements, i.e., it can have elements within it that are of different data types.
  • [100,200,300,400,500] represents an array as well as a list. Whereas, [100,20.50,'finxter'] is essentially a list.

We now have a good understanding of arrays in Python. Let us now dive into our mission-critical question and learn how to declare arrays.

The array Module in Python

Here’s what the official documentation says about Python’s array module –

source: https://docs.python.org/3/library/array.html

Syntax:

from array import *
a = array(typecode, [Initializers])

Note: Type codes are codes that define the type of value the array will hold. Some of the type codes are given below:

Type codeC TypePython TypeMinimum size in bytes
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Example: Let’s create an array of floating types with type code d.

# Importing the array module
import array as arr
a = arr.array('d', [5.2, 10.5, 20.8, 35.9, 50.5])
print(type(a))
# Accessing the Elements of an Array in Python
for i in a:
    print(i)

Output:

<class 'array.array'>
5.2
10.5
20.8
35.9
50.5

Note: To access all the elements from the array, we have to use the “for” loop as shown in the above example.

To access a specific element from the array, we have to use its index. The array index starts from 0 (the first element of the array has index 0.)

Example:

import array as arr
a = arr.array('d', [5.2, 10.5, 20.8, 35.9, 50.5])
print(a)
# Accessing using index
print("First element:", a[0])
print("Third element:", a[2])
print("Last element:", a[-1])

Output:

array('d', [5.2, 10.5, 20.8, 35.9, 50.5])
First element: 5.2
Third element: 20.8
Last element: 50.5

Creating Arrays Using Numpy

You can use the Numpy module to declare arrays in Python. As a matter of fact, the Numpy module has been specifically designed to work with arrays. The NumPy array contains a single data type and is optimized for numerical analysis. 

You need to import the Numpy module to utilize its functions in your program. Further, the array() function of the numpy module is used to create an array that takes a list as an input.

Example:

# Importing the numpy module
import numpy as np 
a = np.array([5.2, 10.5, 20.8, 35.9, 50.5])  
print(a) 
print("The type of array:", type(a)) 

Output:

[ 5.2 10.5 20.8 35.9 50.5]
The type of array: <class 'numpy.ndarray'>

Note: ndarray is the array object in the Numpy module that gets created by the array() function. You can pass a list, tuple, or any object that resembles an array in this function, and it will convert the passed object to a ndarray, as shown in the above example.

Accessing elements from Numpy Array

We can access the elements from the Numpy array with the help of their index as shown below.

Example:

# Importing the numpy module
import numpy as np 
a = np.array([5.2, 10.5, 20.8, 35.9, 50.5])  
print(a) 
# Accessing using index
print("Second element:", a[1])
print("Third element:", a[2])
print("Last element:", a[-1])

Output:

[ 5.2 10.5 20.8 35.9 50.5]
Second element: 10.5
Third element: 20.8
Last element: 50.5

You can perform numerical operations with ease using numpy arrays. Let’s have a look at how we can add two arrays using the Numpy module.  The resultant array will be the addition of two array elements.

Example:

# Importing the numpy module
import numpy as np 
a = np.array([5.2, 10.5, 20.8, 35.9, 50.5]) 
b = np.array([1, 2, 3, 4, 5]) 
print("The addition of the two arrays is:")
print(a + b)

Output:

The addition of the two arrays is:
[ 6.2 12.5 23.8 39.9 55.5]

Numpy arange() in Python

You can also use the arange() method of the NumPy module to create an array in Python. 

Syntax:
np.arange(start ,stop ,step ,dtype)

Here, start represents the first element, and stop represents the last element of the array. The step represents the difference between two consecutive elements, and dtype represents the type of element.

Example:

# Importing the numpy module
import numpy as np 
a = np.arange(5.5, 30, 5) 
print(a)
print(type(a))

Output:

[ 5.5 10.5 15.5 20.5 25.5]
<class 'numpy.ndarray'>

Create an Array using Initializers

Another way to create an array in Python is to use initializers with their default values along with the specified size inside the initializer.

Example:

# Creating an array using initializer
a = [2] * 4
print(a)
b = ['A'] * 5
print(b)

Output:

[2, 2, 2, 2]
['A', 'A', 'A', 'A', 'A']

Creating arrays like lists

We can also create the arrays like lists in Python. We have to use Python’s “for” loop and range() function to initialize the array with the default value.

To add the element at the end of the list, you must use the append() function. You can also use the insert() function to insert an element at the required index.

Example 1:

# Array like lists
a = []
for i in range(5):
    a.append(0)
print(a)

Output:

[0, 0, 0, 0, 0]

Example 2:  In this example we will create a 2D array having 3 rows and 2 columns.

number_of_rows = 3
number_of_columns = 2
arr_2d=[]
for x in range(number_of_rows):
   column_elements=[]
   for y in range(number_of_columns):
       # Enter the all the values w.r.t to a particular column
       column_elements.append(0)
   #Append the column to the array.
   arr_2d.append(column_elements)

print(arr_2d)

Output:

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

Conclusion

We have dealt with numerous ways of declaring an array in Python in this article. Please have a look at the next article, which dives deeper into array declarations (especially 2D arrays or matrices).

I hope this article has helped you. Please stay tuned and subscribe for more interesting discussions and tutorials.


Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy