ProgrammingModerateAccenture · Capgemini pattern

What is printed?

What is printed?
nums = list(range(10))
print(nums[8:2:-2], nums[-3:], nums[2:8:-1])
  1. A. [8, 6, 4, 2] [7, 8, 9] []
  2. B. [8, 6, 4] [9, 8, 7] [7, 6, 5, 4, 3, 2]
  3. C. [7, 5, 3] [7, 8, 9] []
  4. D. [8, 6, 4] [7, 8, 9] []

Correct answer: D. [8, 6, 4] [7, 8, 9] []

With step -2 the slice goes from index 8 down towards 2, stopping before 2: 8, 6, 4. nums[-3:] is the last three in normal order. nums[2:8:-1] asks to walk backwards from 2 to 8, which is impossible, so the result is empty rather than an error.

More Python Programming questions

Exams that ask this topic