Beginner·5 min·basics · slicing
Slicing
You’ll be able to
- Extract sub-sequences with
[start:stop:step]syntax - Reverse sequences with a negative step
- Use slices to insert, delete, and replace multiple items
- Understand the difference between shallow copies and references
Why this matters
Slicing shows up in every pandas DataFrame, NumPy array, and Django queryset. Negative indices and stride tricks like s[::-1] for reversal are staples of LeetCode problems and one-line interview answers.
Common pitfalls
- Off-by-one:
s[0:3]returns 3 chars, not 4. The end index is exclusive; internalize this before touching pandas. - Assuming slicing raises on out-of-range:
s[100:200]on a short string returns'', not an error. Silent bugs. - Confusing
s[-1](last item) withs[:-1](everything but last). Both are common but do opposite things.
seq[start:stop:step] — any of the three can be omitted.
Rules
startdefaults to0,stoptolen(seq),stepto1- Negative indices count from the end (
-1is the last) - The slice never raises on out-of-range — it just clamps
Slicing returns a copy, not a view
b = a[:] is the idiomatic shallow copy of a list.
Try it
- Take every third character of
"abcdefghij". - Get the middle third of a 30-element list.
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
From
nums = [10, 20, 30, 40, 50, 60, 70]print the last three elements — expected:[50, 60, 70]. - Exercise 2
Take
word = "playground"and print it reversed — expected:dnuorgyalp. - Exercise 3
From
s = "abcdefghij"print every third character, starting at the first — expected:adgj.