A program needs to update all values in a list by adding 5 to each number. Which for loop structure accomplishes this task?
To update the actual values inside a list, the program must update each value by itsindex.
The correct code is:
for i in range(len(numbers)):
numbers[i] = numbers[i] + 5
Here, range(len(numbers)) produces valid index positions for the list. The variable i is used to access and update each list element.
Example:
numbers = [10, 20, 30]
for i in range(len(numbers)):
numbers[i] = numbers[i] + 5
print(numbers)
Output:
[15, 25, 35]
Option A does not correctly update the original list:
for number in numbers:
number = number + 5
This changes only the temporary loop variable number, not the actual elements stored inside the list.
Therefore, the correct answer isB.
Bambi
17 days agoCatherin
22 days agoZona
27 days ago