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.
Elouise
7 hours agoDenise
5 days agoAliza
11 days agoDouglass
16 days agoBambi
2 months agoCatherin
2 months agoZona
2 months ago