PY-101 ยท Collections
Sorting and searching
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
sorted(items) returns a new sorted list, while items.sort() sorts the list in place. Both take reverse=True and a key function for custom order, such as key=len. To search, use in to check membership, index() to find a position and min() or max() to pick the extremes.
- Sort with sorted() and sort()
- Sort by key and in reverse
- Search with in, index, count, min and max
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
scores = [72, 95, 88, 61, 95]top = sorted(scores, reverse=True)print("Top 3:", top[:3])print("95 appears", scores.count(95), "times")print("88 is at position", scores.index(88))print("Lowest:", min(scores))print(sorted(["kiwi", "Apple", "fig"], key=str.lower))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
Top 3: [95, 95, 88]
95 appears 2 times
88 is at position 2
Lowest: 61
['Apple', 'fig', 'kiwi'] ๐ฏ players is a list of (name, score) tuples. Print the name of the winner (highest score) and the names sorted by score, highest first.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
max(players, key=lambda p: p[1])[0], then [p[0] for p in sorted(players, key=lambda p: p[1], reverse=True)]
- The problemA game shows the top three scores. You need the scores in order, highest first, and you need to know where a player ranks. That is sorting and searching.
- The Python idea
sorted(items, key=..., reverse=True)sorted(items) returns a new sorted list, while items.sort() sorts the list in place. - In real lifeOnline shops sort products by price, rating or newest with exactly this: sorted(products, key=lambda p: p["price"]).
Start with a question
A game shows the top three scores. You need the scores in order, highest first, and you need to know where a player ranks. That is sorting and searching.
Leaderboards, price filters and "find this order" features are sorting and searching underneath.
Explain it like I'm 10
Sorting is lining your class up by height. Searching is asking "is Ravi in the line, and where is he standing?".
The technical explanation
sorted(nums, reverse=True) sorts high to low. sorted(words, key=len) sorts by length.
Strings sort alphabetically, with capital letters before lower case. Use key=str.lower to ignore case.
items.count(x) counts matches; min() and max() also accept a key.
Syntax
sorted(items, key=..., reverse=True)
items.sort()
x in items items.index(x) Real-world scenario
Online shops sort products by price, rating or newest with exactly this: sorted(products, key=lambda p: p["price"]).
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: String methods โQuestions people ask
How do I sort a list of dictionaries in Python?
Pass a key: sorted(rows, key=lambda r: r["price"]). Add reverse=True for highest first.
Is Python sorting stable?
Yes. Items that compare equal keep their original order, so you can sort by one key and then another.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner How do I sort a list of dictionaries in Python?
Pass a key: sorted(rows, key=lambda r: r["price"]). Add reverse=True for highest first.
beginner Is Python sorting stable?
Yes. Items that compare equal keep their original order, so you can sort by one key and then another.
intermediate Difference between sorted(x) and x.sort()?
sorted returns a new list; sort changes x. sort is in place and returns None.
intermediate sorted([3, 1, 2], reverse=True)?
[3, 2, 1]. Highest first.
Quick revision
Remember
- Sort with sorted() and sort()
- Sort by key and in reverse
- Search with in, index, count, min and max
items.index(x)raises ValueError when x is missing. Checkif x in itemsfirst.
Syntax
sorted(items, key=..., reverse=True)
items.sort()
x in items items.index(x) Official documentation
- Sorting HOW TO (docs.python.org)