Python Sorting
sorted(words) builds a new list and leaves words as it is. words holds soup, then bread, then rice. The new list is ordered by the first letter: b in bread, then r in rice, then s in soup. So the new list is bread, then rice, then soup.
The name ordered is that new list. words is still soup, then bread, then rice. Both lists have length 3. Nothing was added, and nothing was removed. Only the order in the new list is different.
words = ["soup", "bread", "rice"]
ordered = sorted(words)
print(words)
print(ordered)
The first line is soup, then bread, then rice. The second line is bread, then rice, then soup. soup is still first in words. bread is first only in ordered.
words.sort() reorders the list you already have. There is no second list. After it, words itself is bread, then rice, then soup. The call is not that list. If you wrote result = words.sort(), result would be None, and the ordered values would sit in words. That line is not in the program below.
words = ["soup", "bread", "rice"]
words.sort()
print(words)
The screen shows bread, then rice, then soup. soup is no longer first. This is the same list you started with, only the places have changed.
counts starts as 5, then 0, then 2. counts.sort() orders these numbers by size. 0 is smaller than 2, and 2 is smaller than 5, so the list becomes 0, then 2, then 5. The 0 is a stored number. It moves to the front because it is the smallest, not because of the place number.
counts = [5, 0, 2]
counts.sort()
print(counts)
The screen shows 0, then 2, then 5. The length is still 3. No new number appeared, and none was dropped.
The next page is a fixed group, a tuple. This page only puts the values of a list in order. It does not build that group.
Three screens
- What does the first program write, the first line and then the second?
- After words.sort(), what is words?
- What does the third program write?
- If you wrote result = words.sort(), what would result be?
bread before soup
The first screen keeps soup, bread, rice, and then shows bread, rice, soup. words.sort() leaves bread, then rice, then soup in words itself. counts.sort() writes 0, then 2, then 5. result = words.sort() would make result None. The next page is a fixed group. This page only orders a list.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top