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:
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
Arrays values are accessed using the array indexes:
- index of arrays in Python start from 0.
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.
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)
View all Courses