What are arrays in Python?

Arrays are a collection of similar items. In Python, most people use lists instead of arrays. A user can treat lists as arrays but cannot constrain the data type of values stored in a list. Only the same type of data can be stored in arrays. A pictorial representation of arrays is shown below:

svg viewer
  • The length of this array is 5.
  • The data type of values stored in this array is integer.

Defining arrays in Python

To create arrays in Python, we need to import the array module to create arrays. An example of this shown below:

import array as arr # importing the array module
a = arr.array('i',[1,3,5,2,4]) #defining an array of integers with 5 values

'i' is the type for the data type of values in the array. In this case, the array type is of int.

Accessing array values

Arrays values are accessed using the array indexes:

arrayName[indexValue]
  • index of arrays in Python start from 0.

For Example:

Suppose we want to access the value at the 3rd index of the array. The illustration and code snippet below shows how this is done.

svg viewer
import array as arr
a = arr.array('i',[1,3,5,2,4]) # defining an array of integers with 5 values
print("Value at index 3 is: ")
print(a[3])

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved