Skip to the solution
EasyDSA12 min read

How does slicing with start:stop:step work?

1.1k views

The problem

Question presented to candidate: "Explain how seq[start:stop:step] works in Python. What do s[::-1], s[-3:] and s[4:1:-1] give you, and what happens when you assign to a slice?"

What a strong answer should cover:

  • The range is half-open: start is included, stop is excluded, so s[:k] + s[k:] == s and len(s[a:b]) == b - a for in-range bounds.
  • Omitted parts have defaults, negative indices count from the end, and a negative step walks backwards with the defaults flipped (s[::-1] reverses).
  • Slicing clamps out-of-range bounds instead of raising IndexError; only a step of 0 is an error (ValueError).
  • On lists a slice is a new, shallow copy (a[:]), and slice assignment / del a[i:j] can replace, insert or remove regions; extended slices (step != 1) require an equal-size replacement.
  • a[i:j:k] is sugar for a[slice(i, j, k)]; your own __getitem__ receives the slice object, and slice.indices(n) shows the clamped values.

Code / implementation expected: Optional β€” predicting the output of a few slices on a short string or list is the usual check.

  • slicing
  • sequences

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonHalf-open ranges, negative indices, steps, clamping and slice objects
PythonShallow copies, slice assignment, del and a custom __getitem__

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 6 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is the difference between append, extend and insert on a list?

Continue