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

  1. 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.
  2. 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.
  3. print(nums[-2:])
    Start โˆ’2 translates to 5 + (โˆ’2) = 3; omitted stop means 'to the end' โ€” indexes 3, 4 โ†’ [40, 50].
  4. 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 โœ“

Keep practising this rule

More output questions โ†’ All interactive problems