Python Arrays

Learn about arrays in Python and how to work with the array module for efficient numerical operations.

Python Arrays

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

Arrays

Arrays are used to store multiple values in one single variable:

Example - Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Access the Elements of an Array

You refer to an array element by referring to the index number.

Example - Get the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]
x = cars[0]
print(x)

Example - Modify the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Example - Return the number of elements in the cars array:

cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)

Note: The length of an array is always one more than the highest array index.

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example - Print each item in the cars array:

cars = ["Ford", "Volvo", "BMW"]
for x in cars:
    print(x)

Adding Array Elements

You can use the append() method to add an element to an array.

Example - Add one more element to the cars array:

cars = ["Ford", "Volvo", "BMW"]
cars.append("Honda")
print(cars)

Removing Array Elements

You can use the pop() method to remove an element from the array.

Example - Delete the second element of the cars array:

cars = ["Ford", "Volvo", "BMW"]
cars.pop(1)
print(cars)

You can also use the remove() method to remove an element from the array.

Example - Delete the element that has the value "Volvo":

cars = ["Ford", "Volvo", "BMW"]
cars.remove("Volvo")
print(cars)

Note: The list's remove() method only removes the first occurrence of the specified value.

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

append()
Adds an element at the end of the list
clear()
Removes all the elements from the list
copy()
Returns a copy of the list
count()
Returns the number of elements with the specified value
extend()
Add the elements of a list (or any iterable), to the end of the current list
index()
Returns the index of the first element with the specified value
insert()
Adds an element at the specified position
pop()
Removes the element at the specified position
remove()
Removes the first item with the specified value
reverse()
Reverses the order of the list
sort()
Sorts the list

The Array Module

Python has a built-in array module that provides a more efficient way to work with arrays of numeric data.

Example - Import and use the array module:

import array

# Create an array of integers
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers)

# Create an array of floats
floats = array.array('f', [1.1, 2.2, 3.3, 4.4])
print(floats)

Array Type Codes

'b'
signed char (1 byte)
'B'
unsigned char (1 byte)
'h'
signed short (2 bytes)
'H'
unsigned short (2 bytes)
'i'
signed int (4 bytes)
'I'
unsigned int (4 bytes)
'f'
float (4 bytes)
'd'
double (8 bytes)

Array Module Methods

Example - Working with array methods:

import array

# Create an array
arr = array.array('i', [1, 2, 3, 4, 5])

# Append an element
arr.append(6)
print(arr)  # array('i', [1, 2, 3, 4, 5, 6])

# Insert an element at specific position
arr.insert(0, 0)
print(arr)  # array('i', [0, 1, 2, 3, 4, 5, 6])

# Remove an element
arr.remove(3)
print(arr)  # array('i', [0, 1, 2, 4, 5, 6])

# Pop an element
popped = arr.pop()
print(f"Popped: {popped}")  # Popped: 6
print(arr)  # array('i', [0, 1, 2, 4, 5])

# Get array info
print(f"Length: {len(arr)}")
print(f"Type code: {arr.typecode}")
print(f"Item size: {arr.itemsize} bytes")

NumPy Arrays

For more advanced array operations, Python developers often use NumPy, which provides powerful array operations:

Example - NumPy array (requires installation: pip install numpy):

import numpy as np

# Create a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print(arr)

# Array operations
print(arr * 2)      # Multiply all elements by 2
print(arr + 10)     # Add 10 to all elements
print(arr.sum())    # Sum of all elements
print(arr.mean())   # Mean of all elements

# 2D array
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
print(matrix.shape)  # (2, 3)

When to Use Each Type

Python Lists

  • General-purpose, flexible
  • Can store different data types
  • Good for most applications
  • Built-in to Python

Array Module

  • More memory efficient
  • Only stores one data type
  • Good for large numeric datasets
  • Built-in to Python

NumPy Arrays

  • Fastest for numerical operations
  • Advanced mathematical functions
  • Multi-dimensional arrays
  • Requires separate installation