Slicing and sorting

Lists & Tuples, lesson 3 of 6

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

Example

Top of the charts

Try charts[2:] and charts[:-1].

Walkthrough

Where each slice starts and stops

AuraBoltCometDuneEchoFlare012345[:3]stop
Step 1 of 4

charts[:3]: no start means "from the beginning". It stops before index 3: Aura, Bolt, Comet.

in the slice
stepped over
Quiz

What does this print?

Two ways to sort:

  • items.sort() sorts the list in place and returns None.
  • 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.

Example

Rank the scores

Sort a list of names too. Where do names starting with a capital letter go?

Example

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().

Example

Quick stats

min, max, sum and len work on any list of numbers.

Quiz

What does this print?

Exercise

Podium finish

times holds race times in seconds (lower is faster).

  1. Set podium to the three fastest times, fastest first. Don't change times itself!
  2. Set slowest to the slowest time.