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

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

Example

Rank the scores

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

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.