A student needs the first and last quiz result.
What You Need to Understand
Indexes identify list positions: zero means the first element, one the second, and negative indexes count backward from the end. An empty list has no valid element indexes.
When to Use It
A student needs the first and last quiz result.
Step-by-Step Python Example
scores = [78, 92, 85]
print(scores[0])
print(scores[-1])
print(scores[-2])
How the Example Works
The results are 78, 85 and 92. Negative indexing is convenient when list size changes.
Example Output
78
85
92
apple apple
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
fruits = ["pear", "apple", "orange"]
print(fruits[1], fruits[-2])
Important Behavior and Edge Cases
Do not assume scores[len(scores)] is valid; the last valid positive index is len(scores)-1.
Try It Yourself
Read the second item from the beginning and the second from the end of a five-item list.
Common Beginner Mistakes
- Do not assume
scores[len(scores)]is valid; the last valid positive index islen(scores)-1. - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- Indexes identify list positions: zero means the first element, one the second, and negative indexes count backward from the end.
- The results are 78, 85 and 92.
- Do not assume
scores[len(scores)]is valid; the last valid positive index islen(scores)-1.