Foundations-of-Programming-Python practice question 3 of 10

A program needs to update all values in a list by adding 5 to each number. Which for loop structure accomplishes this task?

Full set: 60 questions
Answer options
A: for number in numbers:number = number + 5
B: for i in range(len(numbers)):numbers[i] = numbers[i] + 5 Correct answer
C: for numbers in number:numbers = numbers + 5
Correct Answer:
B. for i in range(len(numbers)):numbers[i] = numbers[i] + 5
Explanation

To modify a list's elements in place during iteration, it is necessary to access them by their index. The range(len(numbers)) function generates a sequence of indices from 0 to the length of the list minus one. The loop then uses each index i to access the element numbers[i], calculate the new value, and assign it back to the same position, thereby updating the original list. Iterating directly over the elements creates a copy, and modifying the copy does not affect the list.

Why Incorrect

A: This loop modifies a temporary loop variable number, not the elements within the original numbers list. C: This syntax is incorrect; it attempts to iterate over an undefined variable number and incorrectly reassigns the list variable numbers.

References

1. Python Software Foundation. (2024). The Python Tutorial, Section 4.3: for Statements. Python 3.12.3 documentation. Retrieved from https://docs.python.org/3/tutorial/controlflow.html#for-statements (This section notes that modifying a sequence while iterating over it can be tricky and often requires creating a new list or iterating over indices.)

2. MIT OpenCourseWare. (2016). 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016, Lecture 4. Retrieved from https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/resources/mit60001f16lec4/ (The lecture covers list mutability and demonstrates iterating by index to modify list elements.)

Scroll to Top