Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Slicing & List Methods

14 min 25 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 2 of 6 · View course roadmap
Step 1

Learn the idea

Slicing extracts sub-lists with list[start:stop:step] — start included, stop excluded:

  • nums[1:3] — items at index 1 and 2
  • nums[:2] — first two; nums[2:] — everything from index 2
  • nums[::-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. Use y = sorted(x) to keep the original.
  • Expecting the stop index to be included: nums[1:3] is two items, not three.
  • reverse=True vs [::-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].

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +25 XP

Blank · autosaved

Given the starter list, print: (1) the first three items as a slice, (2) the list reversed, (3) the sum of all items.

Target output
[5, 3, 8]
[9, 1, 8, 3, 5]
26
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What is "python"[2:4]?
2. Difference between sorted(x) and x.sort()?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path