← Practice
πŸ“– Listslists-top-n
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: sorted(values, reverse=True) returns a new sorted list.

Tests

  • top 3 of unsorted
  • empty input
  • n larger than len
  • n=0
  • duplicates kept (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.