Python 3D Academyবাংলা

Sorting and other list methods

🌍 In real life. A librarian arranges books on a shelf by their numbers, and a teacher writes the class ranking from the highest mark down. Sometimes you rearrange the real shelf; sometimes you only want a sorted copy of the list, like a printed ranking, and the register stays in roll order.

Python has both: one that sorts the list itself, and one that hands you a sorted copy.

The idea in one sentence: nums.sort() puts the list itself in order, while sorted(nums) gives back a new sorted list and leaves the old one alone.

Its words:

  • in place: changing the list itself, as sort() and reverse() do
  • reverse=True: sort largest first: nums.sort(reverse=True)
  • count(x), index(x): how many x, and where the first x is
  • " ".join(words): glue a list of strings into one string

Step by step, for nums = [3, 1, 2]:

  1. nums.sort() rearranges it to [1, 2, 3], smallest first.
  2. nums.reverse() flips the order: [3, 2, 1].
  3. Both changed nums itself; neither gave back a new list.
nums = [3, 1, 2]
nums.sort()
print(nums)
nums.reverse()
print(nums)

Strings sort in alphabetical order, with capital letters before small ones ("Zoe" comes before "amy"). If you want to keep the original list, use sorted(...): it gives you a new sorted list and leaves the old one alone.

words = ["pear", "apple", "fig"]
print(sorted(words))
print(words)

A few more handy methods:

  • a.count(x) says how many times x is in the list.
  • a.index(x) says where the first x is.
  • " ".join(words) glues a list of strings into one string, with " " between them.
letters = ["b", "a", "b", "c"]
print(letters.count("b"))
print(letters.index("c"))
print("-".join(letters))

How Python compares, and what it costs. Python sorts by comparing two items at a time. Numbers compare by size. Strings compare letter by letter by each character's code number, and every capital letter has a smaller code than every small letter, which is why "Zoe" comes before "apple".

Sorting n items takes about n × log₂ n comparisons: for a million items, about 20 million. That's fast, but far more work than one pass, so don't sort inside a loop when once is enough. count() and index() walk the list from the front, like in.

Mistakes and edge cases.

  • Keeping what sort() gives back. nums = nums.sort() throws your list away: sort() changes the list and gives back None.
  • Mixed types. [3, "a"].sort() gives TypeError: '<' not supported between instances of 'str' and 'int'.
  • index() of something missing. ["a"].index("z") gives ValueError: list.index(x): x not in list.
  • join() on numbers. " ".join([1, 2]) gives TypeError: sequence item 0: expected str instance, int found. Turn the numbers into strings first.

Quiz

  1. What does this print?

    a = [5, 2, 9]
    a.sort()
    print(a)
  2. What does this print?

    a = [5, 2, 9]
    b = sorted(a)
    print(a, b)
  3. What does this print?

    print(["x", "y", "x"].count("x"))
  4. What does this print?

    print(", ".join(["red", "blue"]))
  5. How do you sort nums with the largest number first?

    • nums.sort(reverse=True)
    • nums.sort(-1)
    • nums.reverse()
  6. Which line has a mistake?

    nums = [3, 1, 2]
    nums = nums.sort()
    print(nums[0])

Coding tasks

  1. Ask for some words on one line, separated by spaces. Print them in alphabetical order, on one line, with a space between them.

  2. Ask for at least two whole numbers on one line, separated by spaces. Print the second largest (if the largest appears twice, that counts as the second largest too).

  3. Ask for a sentence (words separated by spaces), then ask for one word. Print how many times that word is in the sentence.