Python arrays help you store and manage multiple values in a single variable. They are useful when you need to work with collections of numbers or other data.
Python offers several ways to store multiple values. You can use lists for general-purpose programming, the built-in array module for type-restricted arrays, or NumPy for numerical computations.
In this tutorial, you will learn how to create Python arrays, access elements, update values, add and remove items, and perform basic operations with NumPy.
1. What Is an Array in Python?
An array is a data structure that stores multiple elements under one variable name. Traditional arrays generally store elements of the same data type in a sequence.
Python provides different options for working with array-like data:
Python list: Stores multiple items and can contain different data types.
Python
arraymodule: Stores elements of a specified type, mainly for compact collections of basic values.NumPy array: Supports multidimensional arrays and efficient numerical operations.
Python lists are often the easiest option for beginners. However, the array module and NumPy are useful when your program needs specific array behavior.
2. Why Use Arrays in Python?
Arrays help organize collections of data and make repeated operations easier.
Common benefits include:
Store multiple values in one variable.
Access individual elements using their indexes.
Update, add, or remove elements.
Process numerical data efficiently with suitable libraries.
Represent matrices and multidimensional data using NumPy.
The best option depends on your requirements. Python lists suit general programming, while NumPy is especially useful for scientific and numerical work.
3. How to Create an Array Using Python’s array Module
Python includes a standard library module named array. You do not need to install an external package to use it.
Import the array Module
First, import the module:
import arrayYou can now use array.array() to create an array.
Syntax
array.array(typecode, [elements])Here:
typecodespecifies the type of elements.elementscontains the initial values.
Some commonly used type codes are:
| Type code | Description |
|---|---|
'i' | Signed integer |
'f' | Floating-point number |
'd' | Double-precision floating-point number |
The exact supported type codes and their sizes can depend on the platform. Check Python’s official documentation when you need specific storage sizes.
Example: Create an Integer Array
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers)Output:
array('i', [1, 2, 3, 4, 5])In this example, array.array('i', ...) creates an integer array containing five elements.
Remember that the values must be compatible with the selected type code.
4. How to Access Array Elements in Python
You can access array elements using their index. Python indexing starts at 0, so the first element has index 0.
Consider this example:
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
print(numbers[0])
print(numbers[3])
print(numbers[-1])Output:
1
4
5Here, numbers[0] returns the first element, while numbers[3] returns the fourth element.
Python also supports negative indexes. For example, numbers[-1] returns the last element.
If you access an index outside the array’s valid range, Python raises an IndexError.
5. How to Modify Array Elements
You can change an existing element by assigning a new value to its index.
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
numbers[1] = 10
print(numbers)Output:
array('i', [1, 10, 3, 4, 5])The statement numbers[1] = 10 replaces the second element with 10.
The new value must be compatible with the array’s type code.
6. How to Add Elements to an Array
Python’s array module provides methods to add individual or multiple elements.
Using append()
The append() method adds one element to the end of an array.
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
numbers.append(6)
print(numbers)Output:
array('i', [1, 2, 3, 4, 5, 6])Using extend()
The extend() method adds multiple elements from an iterable.
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
numbers.extend([6, 7, 8])
print(numbers)Output:
array('i', [1, 2, 3, 4, 5, 6, 7, 8])Both methods modify the original array. The added values must match its element type.
7. How to Remove Elements from an Array
You can remove elements using the remove() and pop() methods.
Using remove()
The remove() method deletes the first occurrence of a specified value.
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
numbers.remove(3)
print(numbers)Output:
array('i', [1, 2, 4, 5])If the specified value does not exist, Python raises a ValueError.
Using pop()
The pop() method removes and returns an element. By default, it removes the last element.
import array
numbers = array.array('i', [1, 2, 3, 4, 5])
removed = numbers.pop(2)
print("Removed element:", removed)
print("Updated array:", numbers)Output:
Removed element: 3
Updated array: array('i', [1, 2, 4, 5])The index 2 refers to the third element. You can also use numbers.pop() without an index to remove the last element.
8. How to Find the Length of an Array
Use the built-in len() function to count the elements in an array.
import array
numbers = array.array('i', [10, 20, 30, 40, 50])
print(len(numbers))Output:
5The function returns the number of elements currently stored in the array.
9. Python Arrays Using NumPy
NumPy is a popular Python library for numerical computing. It supports multidimensional arrays and efficient mathematical operations.
Install NumPy
Run the following command in your terminal:
python -m pip install numpyCreate a NumPy Array
import numpy as np
numbers = np.array([1, 2, 3, 4])
print(numbers)Output:
[1 2 3 4]The np.array() function converts the supplied sequence into a NumPy array.
Perform Operations on Array Elements
NumPy supports element-wise arithmetic operations.
import numpy as np
numbers = np.array([1, 2, 3, 4])
print(numbers + 5)Output:
[6 7 8 9]NumPy adds 5 to every element. You do not need to write a separate loop for this operation.
Create a Two-Dimensional Array
NumPy also supports arrays with multiple dimensions.
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(matrix)Output:
[[1 2 3]
[4 5 6]]This example creates a two-dimensional array with two rows and three columns.
10. Difference Between Python Lists, array Module and NumPy Arrays
| Feature | Python list | array module | NumPy array |
|---|---|---|---|
| Mixed data types | Supported | Not generally supported | Usually uses one data type |
| External installation | Not required | Not required | Required |
| Multidimensional operations | Possible with nested lists | No native multidimensional array | Supported |
| Numerical calculations | Usually require loops or other tools | Basic storage and operations | Efficient element-wise operations |
| Common use | General programming | Typed collections | Scientific computing and numerical data |
Choose a Python list for flexible collections. Use the array module when you need a type-restricted sequence of basic values. Choose NumPy for numerical computations and multidimensional arrays.
11. Common Mistakes When Using Python Arrays
Using an Invalid Index
Array indexes start at zero. Accessing an index that does not exist raises an IndexError.
Adding an Incompatible Data Type
An integer array created with array.array('i', ...) cannot accept arbitrary strings as elements.
Confusing Lists with Arrays
Python lists and arrays are different data structures. Lists support flexible element types, while array.array restricts elements to a selected type.
Expecting List-Style Arithmetic from NumPy
Adding a number to a NumPy array performs element-wise addition. Adding a number to a Python list does not work in the same way.
FAQs
Does Python support arrays?
Python’s standard language does not provide a dedicated built-in array type like some other programming languages. However, it provides lists, the standard-library array module, and external libraries such as NumPy.
What is the difference between a Python list and an array?
A list can store items of different data types. The array module stores elements of a specified type, while NumPy provides efficient numerical and multidimensional operations.
How do you create an array in Python?
Import the array module and call array.array() with a type code and initial values. For example, array.array('i', [1, 2, 3]) creates an integer array.
How do you add an element to an array?
Use append() to add one element. Use extend() to add multiple elements from an iterable.
When should you use NumPy arrays?
Use NumPy when you need numerical computations, element-wise operations, matrices, multidimensional arrays, or scientific data processing.
