Lesson 31 of 60
โฎPrev Nextโฏ

PY-101 ยท Collections

Sorting and searching

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

31of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    Sorting and searching, running
    1. scores = [72, 95, 88, 61, 95]
    2. top = sorted(scores, reverse=True)
    3. print("Top 3:", top[:3])
    4. print("95 appears", scores.count(95), "times")
    5. print("88 is at position", scores.index(88))
    6. print("Lowest:", min(scores))
    7. print(sorted(["kiwi", "Apple", "fig"], key=str.lower))
    Press โ–ถ to watch Python run this, one line at a time.
    1. 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.
    2. The Python ideasorted(items, key=..., reverse=True)sorted(items) returns a new sorted list, while items.sort() sorts the list in place.
    3. 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)

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Online shops sort products by price, rating or newest with exactly this: sorted(products, key=lambda p: p["price"]).

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Difference between sorted(x) and x.sort()?
    2. 2. sorted([3, 1, 2], reverse=True)?
    3. 3. [5, 6, 5].count(5)?
    4. 4. ["b", "a"].index("a")?
    5. 5. sorted(["bb", "a", "ccc"], key=len)?

    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. Check if x in items first.

    Syntax

    sorted(items, key=..., reverse=True)
    items.sort()
    x in items    items.index(x)

    Official documentation