Data Structures – Arrays in Python

Does Python have arrays?

After variables, arrays are generally the most commonly used data structure. An array is similar to a list in Python. Actually, a Python list can do everything an array, say in Java, can do (and more). Strictly speaking, an array provides a sequence of indexed and homogeneous (identically typed) data items organized in contiguous memory locations for efficient memory management. Arrays can be one-dimensional (like a list of numbers) or two-dimensional (like a grid or matrix). One can even create k-dimensional arrays, although this sort of organization can be hard to conceptualize.

Python does provide arrays through its libraries (e.g. NumPy, Python built-in array). Python beginners should, however, think of lists as Python’s arrays. When someone refers to arrays in Python, they often mean lists. Once a student programs in another language and uses arrays with a smaller set of supported operations, they will appreciate the flexibility lists in Python provide.

An example of using Python arrays

## import the array package
from array import array

## creating an array of integers
myArray = array('l', [1, 2, 3, 4, 5]) # The first argument 'l' means integers (think 'l' for 'long')

myArray[0] #returns the first element which is 1

##Changing an element in an array
myArray[0] = 10
print myArray 	# prints array('l', [10, 2, 3, 4, 5])

##You cannot assign other types of values to an array element
##Doing so will produce a TypeError.
myArray[0] = 'Bill' # TypeError: an integer is required