Array access
- Algorithms course
- Beginner
- Lesson 10/80
- 4 min
Learn 0-based indexing and O(1) access.
Looping through an array
To visit every element of an array, use a for x in arr: loop. This processes each element in order.
If you also need the index, write for i in range(len(arr)):. This lets you use both the index and the element.
Printing an array
To print each element on its own line, call print(x) inside the loop. This takes O(n) time.
To see the whole array on one line, print(arr) is enough; it shows the list representation of the array.
Practice Print array
Write print_all(arr). Print each element with for. Call print_all([5, 10, 15]) to print 5, 10, 15.
Starter code
def print_all(arr):
# Print each elementSample solution
def print_all(arr):
# Print each element
for x in arr:
print(x)
print_all([5, 10, 15])Expected output
5 10 15
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Loop structure
To iterate array elements: ____ x in arr:
To iterate array elements: for x in arr:
Explanation: for is right.
2 Array access: match the terms
| Term | Meaning |
|---|---|
for |
Loop |
len(arr) |
Length |
range |
Range |
print |
3 What does len(arr) return?
- The first element
- The last element
- The number of elements Correct answer
- The index
Explanation: len(arr) returns the number of elements.