← Back to course
Code Crew G5 / Week 08 / Thursday
4/6
Week 08 Β· Sorting by hand

Thursday

Let Python sort
// Selection sort and sorted()
⏱ about 15 min

Thursday: Let Python sort

Rocket is proud of his selection sort. Then Nova whispers that Python has its own sorting tools.

"So I did all that for nothing?" Rocket says.

Raven shakes her head. "What do you notice now when you sort cards by hand?"

"I know what is happening inside," Rocket says. "I can count the work."

Nova twirls. "Exactly! Here is a hint. One tool makes a new list, and one changes the old list."

sorted() and .sort()

ids = [27, 3, 15, 8]
print(sorted(ids))
print(ids)
ids.sort()
print(ids)
print(sorted(ids, reverse=True))
Output:
[3, 8, 15, 27]
[27, 3, 15, 8]
[3, 8, 15, 27]
[27, 15, 8, 3]
  • sorted(ids) makes a new sorted list. The old list stays the same.
  • ids.sort() sorts the list itself. The old order is gone.
  • reverse=True sorts from biggest to smallest.
StatementTrue or false?
sorted() changes the original list.?
.sort() changes the original list.?
sorted(ids, reverse=True) puts the biggest number first.?
WHY THIS EXERCISEKnowing which tool changes the list helps you avoid losing data you still need.

Sorting words

Words sort in alphabet order. But every capital letter comes before every small letter.

print(sorted(["Iris", "Ember", "Halo"]))
print(sorted(["glow", "Halo", "ember"]))
Output:
['Ember', 'Halo', 'Iris']
['Halo', 'ember', 'glow']
PREDICT THE SORTED ORDER.
  • Read the question.
  • Tap your answer.
What is first in sorted(["Pip", "Juno", "Lumen"])?
What is first in sorted(["frost", "Iris"])?
What is the last item of sorted([12, 40, 7, 31])?
WHY THIS EXERCISEWithout reverse=True, the biggest item ends up last.

Practice lab: sort it out

names = ["Pip", "ash", "Juno"]
print(sorted(names))
nums = [5, 1, 4]
nums.sort(reverse=True)
print(nums)
print(sorted([3, 3, 1]))
What is the first word in the first line?
What is the last word in the first line?
What is the first number in the second line?
What is the first number in the last line?
TOOL CHECK
  • Read the question.
  • Tap your answer.
After sorted(names), is names still ["Pip", "ash", "Juno"]?
What is nums after nums.sort(reverse=True)?
What is first in sorted(["b", "a", "C"])?
StatementTrue or false?
sorted([3, 3, 1]) keeps both 3s.?
nums.sort() makes a new list and keeps the old one.?
reverse=True works with sorted() and .sort().?
"Juno" sorts before "Pip".?
WHY THIS EXERCISEPick sorted() to keep the old order, or .sort() to replace it.
What is the last item of sorted([9, 2, 14, 6], reverse=True)?
WHY THIS EXERCISEreverse=True puts the smallest item at the end.

Great job! Now you can sort by hand, in your own code, or with one Python word. Tomorrow we sort star records and then search them.

← Wednesday