What is an array?
- Algorithms course
- Beginner
- Lesson 9/80
- 4 min
Learn that an array stores same-type elements in contiguous memory.
What is an array?
An array is a data structure where elements of the same type are stored contiguously in memory. Each element has an index and access is O(1).
Indices start at 0: the first element is arr[0], the second arr[1]. The length is obtained with len(arr).
Array access
To access an element, write arr[index]. Access takes O(1) time because the address is computed directly.
An invalid index raises an error. For example, accessing arr[5] in a 3-element array raises an out-of-bounds error.
Practice Access element
Write get_element(arr, i). Return arr[i]. Print 20 with print(get_element([10, 20, 30], 1)).
Starter code
def get_element(arr, i):
# Return elementSample solution
def get_element(arr, i):
# Return element
return arr[i]
print(get_element([10, 20, 30], 1))Expected output
20
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the index of the first element?
- 1 Correct answer
- 0
- -1
- n
Explanation: The first element has index 0.
2 Array access
To access the third element: arr[____]
To access the third element: arr[2]
Explanation: 2 is right.
3 What is an array: match the terms
| Term | Meaning |
|---|---|
arr[0] |
First element |
len(arr) |
Length |
O(1) |
Access |
index |
Position |