Home โบ Output practice โบ Print a list slice
Predict the output: list slicing
๐ฎ Predict the outputTopic: listsDifficulty: easyNo login needed
The snippet
Three slices of the same five-element list. Every one of them is governed by a single rule โ slices include the start, exclude the stop โ plus the meaning of a negative start and a step. Write all three printed lines before revealing.
nums = [10, 20, 30, 40, 50]
print(nums[1:4])
print(nums[-2:])
print(nums[::2])
Your prediction
Type exactly what this program prints โ one line per print() call:
The output
[20, 30, 40]
[40, 50]
[10, 30, 50]
Line-by-line explanation
nums = [10, 20, 30, 40, 50]
Five elements at indexes 0โ4. Keep both index rows in mind: 0..4 from the front, -5..-1 from the back.print(nums[1:4])
Half-open interval: start 1 included, stop 4 excluded โ indexes 1, 2, 3 โ[20, 30, 40]. Length is stop โ start = 3.print(nums[-2:])
Start โ2 translates to 5 + (โ2) = 3; omitted stop means 'to the end' โ indexes 3, 4 โ[40, 50].print(nums[::2])
Both bounds omitted, step 2: take index 0, skip one, repeat โ indexes 0, 2, 4 โ[10, 30, 50].
Share your result
Challenge a friend โ the link contains the question, never the answer:
Copied โ