Back

Activity 1.19: len() and Safe Access

divider

Activity 1.19

len() and Safe Access

Key Concepts

len()

Safe Last-Index Access

Hardcoding Is Fragile

Activity 1.18 accessed the last food with foods[4] — but that only works because the list has exactly 5 elements. Add or remove one, and 4 is wrong.

scores = [84, 91, 76, 88, 95]
print(scores[4])

len()

len() returns how many elements a list has — right now, not whenever you last counted.

scores = [84, 91, 76, 88, 95]
print(len(scores))

len()

Terminal window
5

The Last Valid Index

A list of length 5 has valid indexes 0 through 4 — so the last index is always len(list) - 1, no matter how long the list is.

scores = [84, 91, 76, 88, 95]
last_index = len(scores) - 1
print(scores[last_index])

The Last Valid Index

Terminal window
95

The Off-by-One Mistake

Forget the - 1, and you're asking for one index past the end of the list — Python won't guess what you meant.

scores = [84, 91, 76, 88, 95]
print(scores[len(scores)])

The Off-by-One Mistake

Terminal window
IndexError: list index out of range

A crash, not a quiet wrong answer — which makes this particular mistake easy to catch.

Today's Objectives

  • Finding a list's length with len()
  • Computing the last valid index without hardcoding it
  • Recognizing the off-by-one mistake before it happens

Key Terms

len()
Built-in function that returns how many elements a list has.
Off-by-One Error
A mistake where an index is one too high or one too low — often from forgetting len(list) - 1.

'F' → Fullscreen

divider

Build

Create a new Python program named 1-19-len-and-safe-access.


Task 1: Find the Length

  • Create a list of 5 quiz scores and print how many scores it has, using len().
len() and Safe Access
scores = [84, 91, 76, 88, 95]
print(f"Number of scores: {len(scores)}")

Task 2: Access the Last Element Safely

  • Compute the last valid index with len(scores) - 1, then print the last score.
len() and Safe Access
scores = [84, 91, 76, 88, 95]
print(f"Number of scores: {len(scores)}")
last_index = len(scores) - 1
print(f"Last score: {scores[last_index]}")

Task 3: Update Without Hardcoding

  • Update the first and last scores using 0 and last_index — no hardcoded numbers.
len() and Safe Access
scores = [84, 91, 76, 88, 95]
print(f"Number of scores: {len(scores)}")
last_index = len(scores) - 1
print(f"Last score: {scores[last_index]}")
scores[0] = 100
scores[last_index] = 100
print(f"Updated scores: {scores}")
divider

Checkpoint

Verify your program works correctly.

Example Output
Number of scores: 5
Last score: 95
Updated scores: [100, 91, 76, 88, 100]
divider

Reflection

Answer the following questions before submitting your work.

  1. Why is len(scores) - 1 the last valid index instead of len(scores)?
  2. What happens if you try to access scores[len(scores)]?
  3. Why is using len() better than hardcoding an index number like 4?
divider

Submit

Submit the required files to the appropriate dropbox.

Activity Complete