Trusted answers to developer questions

What are arrays in Python?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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])

RELATED TAGS

array
python
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?