Slicing & List Methods
Lesson 2 of 6 · View course roadmap
Learn the idea
Slicing extracts sub-lists with list[start:stop:step] — start included, stop excluded:
nums[1:3]— items at index 1 and 2nums[:2]— first two;nums[2:]— everything from index 2nums[::-1]— the classic reverse trick
Essential methods and functions: sorted(nums) (returns a new sorted list), nums.sort() (sorts in place), sum(nums), min(nums), max(nums), nums.count(x), nums.remove(x), nums.pop().
Strings slice exactly the same way: "python"[0:2] → "py".
Where you'll use this
Slicing is data science's daily bread: first 100 rows to preview (rows[:100]), last week of readings (data[-7:]), every second sample (signal[::2]). Pandas and NumPy extend this exact syntax.
Common mistakes
y = x.sort()— .sort() sorts in place and returns None, so y is None. Usey = sorted(x)to keep the original.- Expecting the stop index to be included:
nums[1:3]is two items, not three. reverse=Truevs[::-1]: .sort(reverse=True) sorts descending; [::-1] merely reverses current order.
Pro tip
Slices never raise IndexError — "abc"[10:20] is just "". That makes truncation safe in one line: preview = text[:280].
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +25 XP
Given the starter list, print: (1) the first three items as a slice, (2) the list reversed, (3) the sum of all items.
[5, 3, 8] [9, 1, 8, 3, 5] 26
data[:3], data[::-1], sum(data).
data = [5, 3, 8, 1, 9] print(data[:3]) print(data[::-1]) print(sum(data))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.