350-401 · Question #1178
Refer to the exhibit. What is output by this code?
The correct answer is B. 8 7 6 5. The Python code iterates four times, printing elements from the list my_list using negative indexing to access elements from the end backward.
Question
Refer to the exhibit. What is output by this code?
Options
- A-1 -2 -3 -4
- B8 7 6 5
- C4 5 6 7
- D-4 -5 -6 -7
How the community answered
(27 responses)- A11% (3)
- B81% (22)
- C4% (1)
- D4% (1)
Why each option
The Python code iterates four times, printing elements from the list `my_list` using negative indexing to access elements from the end backward.
The code retrieves positive integer values from the list, not negative ones, and accesses them from the end, not starting from -1.
The code uses negative indexing in Python, where `my_list[-1]` refers to the last element (8), `my_list[-2]` to the second to last (7), and so on. The `range(4)` loop means `x` takes values 0, 1, 2, 3. For `x=0`, it prints `my_list[-1]` (8); for `x=1`, `my_list[-2]` (7); for `x=2`, `my_list[-3]` (6); and for `x=3`, `my_list[-4]` (5), resulting in '8 7 6 5' with spaces.
This output would occur if positive indexing were used or the list was traversed in a different order, which is not what `my_list[-(x+1)]` achieves.
The elements in `my_list` are positive numbers, and the negative indexing only dictates position, not the sign of the retrieved value.
Concept tested: Python list negative indexing and loops
Source: https://docs.python.org/3/tutorial/introduction.html#lists
Topics
Community Discussion
No community discussion yet for this question.