Looping over an array
- Algorithms course
- Beginner
- Lesson 11/80
- 4 min
Loop over an array with for and compute a sum.
Searching in an array
To find a specific element in an array, use linear search: check each element in order. The worst case is O(n).
If the element is found, its index is returned; if not, -1 is returned. This does not require the array to be sorted.
Updating an array
To update an element, write arr[i] = new_value. This takes O(1) time because access is by index directly.
Updating does not change the array's size in memory; it only changes the value of one element.
Practice Array sum
Write sum_all(arr). Sum elements with for and return. Print 12 with print(sum_all([2, 4, 6])).
Starter code
def sum_all(arr):
# Compute sumSample solution
def sum_all(arr):
# Compute sum
total = 0
for x in arr:
total = total + x
return total
print(sum_all([2, 4, 6]))Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Looping over an array: match the terms
| Term | Meaning |
|---|---|
arr[i] |
Access |
arr[i] = v |
Update |
len(arr) |
Length |
for x in arr |
Loop |
2 How long does array update take?
- O(n^2) Correct answer
- O(1)
- O(n)
- O(log n)
Explanation: Array update is O(1).
3 Update
Update the second element: arr[1] = ____
Update the second element: arr[1] = 42
Explanation: 42 is right.