BeginnerCoder

Lesson 8 — Ordering & limit

Sort, then take the first few

Django sorts with .order_by("age") (oldest last) or .order_by("-age") (the minus means descending — biggest first), and limits with slicing: [:2] = the first two.

In Python: sorted(posts, key=lambda p: p["likes"], reverse=True)[:3]. A lambda is a tiny unnamed function; here it tells sorted which value to compare.

Note: the exercise runs in your browser without Django installed, so it is a small plain-Python simulation of what Django does for you.

Why it matters: "top 10", "latest 5 posts", "cheapest first" — every list page sorts and limits.

Want it another way?
Task

Print the names of the 2 oldest users, oldest first.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.