📋 Lists & Tuples, lesson 3 of 6
Slicing and sorting
Grab parts of a list, sort it, and get quick stats.
10 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Slicing works just like with strings:
items[start:stop:step] gives you a new list
from start up to (not including) stop. Leave a
number out to go from the beginning or to the end.
Top of the charts
Try charts[2:] and charts[:-1].
Where each slice starts and stops
charts[:3]: no start means "from the beginning". It stops before index 3: Aura, Bolt, Comet.
What does this print?
Two ways to sort:
items.sort()sorts the list in place and returnsNone.sorted(items)returns a new sorted list and leaves the original alone.
Add reverse=True for largest first. Numbers sort
by value. Strings sort by their characters, with
every capital letter before every lowercase one
("Zebra" < "apple") — so for true alphabetical
order, sort lowercased copies.
Rank the scores
Sort a list of names too. Where do names starting with a capital letter go?
Going backwards
reversed(charts) walks a list backwards without changing
it; wrap it in list() to see the values. charts[::-1]
also gives a reversed copy, but charts.reverse() flips
the list in place, just like sort().
Quick stats
min, max, sum and len work on any list of numbers.
What does this print?
Podium finish
times holds race times in seconds (lower is
faster).
- Set
podiumto the three fastest times, fastest first. Don't changetimesitself! - Set
slowestto the slowest time.