← Practice
πŸ“– ListsLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 2/5Β·~12 min

Lists: top N values

Lists

Lists hold multiple values in order:

python
fruit = ["apple", "banana", "cherry"]
fruit[0]            # "apple"   β€” indices start at 0
fruit[-1]           # "cherry"  β€” negative counts from the end
fruit.append("kiwi")
len(fruit)          # 4

You can iterate over a list with for:

python
for item in fruit:
    print(item)

Your task

Write a function top_n(values, n) that returns the n largest numbers from values, sorted from largest to smallest.

If n is greater than len(values), return all of them sorted.

python
top_n([3, 1, 4, 1, 5, 9, 2, 6], 3)   # [9, 6, 5]
top_n([], 5)                          # []
top_n([1, 2, 3], 10)                  # [3, 2, 1]

Hint: if the numbers were ordered largest-first, the answer would be sitting right at the front of the list. Two moves: order them that way, then take the front portion. Which sorted option flips the direction, and which slice grabs the first n?

Tests

  • top 3 of unsorted
  • empty input
  • n larger than len
  • n=0

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.