loop
Operations on lists

Module 3 · Operations on lists · Lesson 2 of 5

Powerful slices

You just used a slice to copy a list. A slice is a way to pull out a whole stretch of a list at once. Where nums[2] grabs a single item, nums[1:4] grabs a whole range as a brand-new list.

nums[1:4]
010
120
230
340
450
↓ new list
203040

Like range, the stop 4 is excluded — you get indices 1, 2 and 3.

The two numbers are a start and a stop, and — just like range — the stop is excluded. The real power is that you can leave parts out: nums[:3] means “from the beginning,” nums[2:] means “to the end,” and there's an optional third number — the step.

Run it yourselfruns in your browser · Python
main.py

Slices aren't only for reading. Put one on the left of an = and you can replace a whole stretch at once — even with a different number of elements — and del with a slice removes a stretch entirely.

Run it yourselfruns in your browser · Python
main.py

One slice notation, four jobs: copy, read, replace, delete. Next we'll point those same slices at the end of a list with negative indices.