Python Arrays
Arrays
An array is a data structure that stores multiple values in a single variable, with each value accessible by its position.
Instead of creating many separate variables:
item1 = "Pen"
item2 = "Pencil"
item3 = "Eraser"
you can store all the values together in one array:
stationery = ["Pen", "Pencil", "Eraser"]
This makes your code cleaner and easier to manage, especially with large amounts of data. Imagine storing 500 student names in 500 separate variables — and then trying to loop through them. With an array, one variable holds them all, and a single loop can process every item.
Arrays in Python: Lists
Python does not have a separate built-in "array" syntax like C or Java. Instead, Python's list fills the role of an array in everyday programming. When Python tutorials talk about "arrays" at the beginner level, they almost always mean lists, and that is how this lesson uses the term.
| Feature | Python List (used as an array) |
|---|---|
| Syntax | Square brackets [ ] |
| Ordered | Yes |
| Indexed | Yes, starting at 0 |
| Changeable | Yes |
| Size | Grows and shrinks automatically |
| Item types | Any — and different types can be mixed |
Note: Python also offers true typed arrays through the standard-library
arraymodule and the popular third-party NumPy library. These are covered briefly at the end of this lesson.
Creating an Array
Arrays (lists) are created with square brackets, with values separated by commas.
fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits)
Expected output:
['Apple', 'Banana', 'Mango', 'Orange']
Accessing Array Elements
Each element has an index number. Indexing starts at 0, so the first element is at index 0.
| Element | "Apple" | "Banana" | "Mango" | "Orange" |
|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 |
fruits = ["Apple", "Banana", "Mango", "Orange"]
print(fruits[0]) # First element
print(fruits[2]) # Third element
print(fruits[-1]) # Last element
Expected output:
Apple
Mango
Orange
A negative index counts from the end: -1 is the last element.
Accessing an index that does not exist raises an error:
print(fruits[4])
Output:
IndexError: list index out of range
Modifying Array Elements
Change an element by assigning a new value to its index.
fruits = ["Apple", "Banana", "Mango", "Orange"]
fruits[1] = "Grapes"
print(fruits)
Expected output:
['Apple', 'Grapes', 'Mango', 'Orange']
The value at index 1 ("Banana") is replaced with "Grapes". The other elements are unchanged.
Length of an Array
Use len() to find how many elements an array contains.
fruits = ["Apple", "Grapes", "Mango", "Orange"]
total_items = len(fruits)
print(total_items)
Expected output:
4
Remember: The highest valid index is always length − 1. For an array of 4 elements, the indexes are 0, 1, 2, and 3.
Looping Through an Array
Use a for loop to visit every element.
fruits = ["Apple", "Grapes", "Mango", "Orange"]
for fruit in fruits:
print("Fruit:", fruit)
Expected output:
Fruit: Apple
Fruit: Grapes
Fruit: Mango
Fruit: Orange
If you also need the index, use enumerate():
for index, fruit in enumerate(fruits):
print(index, fruit)
Expected output:
0 Apple
1 Grapes
2 Mango
3 Orange
Adding Elements to an Array
append() adds a new element to the end of the array.
fruits = ["Apple", "Grapes", "Mango", "Orange"]
fruits.append("Pineapple")
print(fruits)
Expected output:
['Apple', 'Grapes', 'Mango', 'Orange', 'Pineapple']
To add an element at a specific position, use insert(index, value).
Removing Elements From an Array
Remove by Index With pop()
pop(index) removes the element at the given index and returns it.
fruits = ["Apple", "Grapes", "Mango", "Orange", "Pineapple"]
fruits.pop(2) # Removes the element at index 2
print(fruits)
Expected output:
['Apple', 'Grapes', 'Orange', 'Pineapple']
"Mango" was at index 2, so it is removed. The elements after it shift one position to the left.
Remove by Value With remove()
remove(value) deletes the first element that matches the value.
fruits = ["Apple", "Grapes", "Orange", "Pineapple"]
fruits.remove("Apple")
print(fruits)
Expected output:
['Grapes', 'Orange', 'Pineapple']
If the value does not exist, remove() raises a ValueError.
Practical Example: Average Marks
marks = [78, 92, 65, 88, 70]
total = 0
for mark in marks:
total += mark
average = total / len(marks)
print("Highest:", max(marks))
print("Lowest:", min(marks))
print("Average:", average)
Expected output:
Highest: 92
Lowest: 65
Average: 78.6
Storing all marks in one array lets you calculate statistics with a loop and built-in functions — no matter how many marks there are.
Typed Arrays: The array Module
The standard library's array module provides arrays that hold only one numeric type. Because every element has the same type, these arrays store numbers more compactly than lists.
from array import array
numbers = array("i", [10, 20, 30])
numbers.append(40)
print(numbers)
print(numbers[1])
Expected output:
array('i', [10, 20, 30, 40])
20
The type code "i" means "signed integer". Adding a value of the wrong type raises an error:
numbers.append(2.5)
Output:
TypeError: 'float' object cannot be interpreted as an integer
Lists vs the array Module vs NumPy
| Feature | List | array module | NumPy array |
|---|---|---|---|
| Built in | Yes | Yes (standard library) | No — install with pip install numpy |
| Element types | Any, can be mixed | One numeric type | One type |
| Memory use | Higher | Lower | Lower |
| Math on whole arrays | No | No | Yes (for example, arr * 2) |
| Best for | General-purpose collections | Large sequences of plain numbers | Scientific computing and data analysis |
For most programs — and for the rest of this course — a list is the right choice.
Common Mistakes
| Mistake | Problem |
|---|---|
Using index len(array) | IndexError; the last index is len(array) - 1 |
| Removing a value that is not present | ValueError from remove() |
Expecting pop() without an index to remove the first item | pop() removes the last item by default |
Assuming Python has a built-in array type like C | Use lists, or import the array module |
Related Concepts
- Python Lists — the full guide to lists
- Python Array Methods — all methods available on lists/arrays
- Python for Loops — iterating over arrays