List Methods: append, sort, len

Pre-COSMOS Day 4, for Cluster 10: Robot Inventors, covered in depth. It grows a list with append(), orders it with sort() and sort(reverse=True), and counts with len(), building to the big idea that in-place methods return None - so nums = nums.sort() wipes your data. It then builds the High-Score Board project, with a top-three stretch. Every snippet is runnable, and the outputs and error messages came verbatim from CPython 3.12.

Subject: Python · 69 slides · code lesson

Open the interactive version of this deck · Homework for this lesson

What this lesson covers

The lesson, slide by slide

1. What you will be able to do

Objectives

As your robot runs, you pile up readings in a list. To manage that list you need the methods that change it in place. By the end you can:

1. Use append() to add one reading to the end of a list, in place.

2. Use sort() to order a list - and sort(reverse=True) for high-to-low.

3. Use len() to count how many items a list holds.

4. Explain why nums = nums.sort() throws your data away.

5. Build a High-Score Board: append scores, sort them, and print a ranked list.

2. What survived from for Loops?

Warm-up

Discussion prompt

Before we open List Methods: append, sort, len: without looking back, what was the main idea of for Loops, and what could you do by the end of it that you could not do before?

Hint: One sentence for the idea, one for the skill. If the second one is blank, that is the part to revisit.

Answer:

That session covers what a for loop does, range() and the off-by-one trap, and the accumulator pattern. Every snippet is runnable, and every trace table came from real execution.

3. A list is an ordered collection

Concept

A list holds many values in order, inside square brackets: [3, 1, 2]. Each item has a position, and the list can grow while your program runs.

list — An ordered, changeable collection of values. As a robot takes readings, you append each one onto a list so they pile up in order.

4. Break it if you can: A list is an ordered collection

Counterexample

Discussion prompt

A list holds many values in order, inside square brackets: [3, 1, 2]. Each item has a position, and the list can grow while your program runs.

That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.

Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.

5. The big idea: changing a list "in place"

Concept

Some list tools change the list itself - they add to it or rearrange it without making a new copy. That is called changing it in place.

in place (mutate) — To change the original list directly instead of building a new one. append() and sort() both mutate the list in place - the same list, now different.

6. Take the definitions apart: list vs in place (mutate)

Definition probe

Sort into buckets

Every line below is part of the definition of list or of in place (mutate) — one or the other, never both. Put each where it belongs.

list
An ordered, changeable collection of values.; As a robot takes readings, you append each one onto a list so they pile up in order.
in place (mutate)
To change the original list directly instead of building a new one.; append() and sort() both mutate the list in place - the same list, now different.
b1
An ordered, changeable collection of values. As a robot takes readings, you append each one onto a list so they pile up in order.
b2
To change the original list directly instead of building a new one. append() and sort() both mutate the list in place - the same list, now different.

7. Your list is a whiteboard, not a photocopy

Intuition

Picture your list as a whiteboard. append() walks up and writes one more item on it. sort() erases and rewrites the items in order. The board is changed - you are not handed a new board.

That is why these tools don't need to hand anything back: the work already happened to your list. Hold onto that idea - it explains the biggest trap in this lesson.

8. By analogy: Your list is a whiteboard, not a photocopy

Analogy

Discussion prompt

Explain Your list is a whiteboard, not a photocopy by analogy to something with no Python in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.

Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.

Answer:

Picture your list as a whiteboard. append() walks up and writes one more item on it. sort() erases and rewrites the items in order. The board is changed - you are not handed a new board.

9. append(): add one item to the end

Concept

nums.append(x) sticks x onto the end of nums, making the list one longer. It changes nums in place.

10. Teach it back: append(): add one item to the end

Explain it

Discussion prompt

Explain append(): add one item to the end to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.

Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.

Answer:

nums.append(x) sticks x onto the end of nums, making the list one longer. It changes nums in place.

11. What has to happen first: append in action

Ranking

Put in order

Put the moves of append in action into the order they have to happen.

  1. Line 1: start with three items
  2. Line 2: append(4) adds 4 to the end
  3. Trace the list

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. nums is now [3, 1, 2, 4]. It grew in place - same list, one longer.

12. append in action

Worked example

nums = [3, 1, 2]
nums.append(4)
print(nums)

Line 1: start with three items

Why: nums is [3, 1, 2] - positions 0, 1, 2.

Line 2: append(4) adds 4 to the end

Why: nums is now [3, 1, 2, 4]. It grew in place - same list, one longer.

Trace the list

Why: Verified by execution: prints [3, 1, 2, 4].

stepcodenums nowlen
1nums = [3, 1, 2][3, 1, 2]3
2nums.append(4)[3, 1, 2, 4]4
3print(nums)[3, 1, 2, 4]4

13. Fill in: code for append in action

Comparison

Comparison matrix

From append in action: refill the code column from what you know. The rest of the table is as it appeared.

stepcodenums nowlen
1nums = [3, 1, 2][3, 1, 2]3
2nums.append(4)[3, 1, 2, 4]4
3print(nums)[3, 1, 2, 4]4

14. append adds exactly ONE item

Concept

append() always adds its argument as a single item. If you append a whole list, that list becomes one item inside your list - it does not merge in.

15. Something is wrong here: appending a list nests it

Anomaly

Predict first

A student writes this, and it looks reasonable:

Goal: add 3 and 4 onto [1, 2].

It is wrong. Say what breaks — and say it before you turn the page.

Correct: nums is [1, 2, [3, 4]] - length 3, not 4.

To add the numbers separately, join with + (or append each one).

Why: nums is [1, 2, [3, 4]] - length 3, not 4. The [3, 4] is a single nested item, not two new numbers.

16. Trap: appending a list nests it

Trap

The trap

Goal: add 3 and 4 onto [1, 2].

nums = [1, 2]
nums.append([3, 4])
print(nums)
print(len(nums))

append put the whole list in as one item

Why: nums is [1, 2, [3, 4]] - length 3, not 4. The [3, 4] is a single nested item, not two new numbers.

expressionvalue
nums[1, 2, [3, 4]]
len(nums)3

The fix

To add the numbers separately, join with + (or append each one).

nums = [1, 2]
nums = nums + [3, 4]
print(nums)
print(len(nums))

+ builds one flat list

Why: nums is [1, 2, 3, 4] - length 4. (Or call nums.append(3) then nums.append(4) to add them one at a time.)

expressionvalue
nums[1, 2, 3, 4]
len(nums)4

17. What each one costs: Trap: appending a list nests it

Trade off

Comparison matrix

From Trap: appending a list nests it: every row here is a choice with a cost. Fill the value column, then say which row you would actually pick and what you give up for it.

expressionvalue
nums[1, 2, [3, 4]]
len(nums)3

18. sort(): put a list in order

Concept

nums.sort() rearranges nums from smallest to largest, in place. The same list is reordered - you don't get a new one back.

19. Predict the next row: Sorting low to high

Pattern

Predict first

The table runs: 1 | nums = [3, 1, 2] | [3, 1, 2] · 2 | nums.sort() | [1, 2, 3]

In Sorting low to high, given the rows so far: what is the next one — the row where step is 3?

Correct: 3 | print(nums) | [1, 2, 3]

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

Why: The relationship between the columns, not the individual numbers, is what generates the next row. Smallest to largest: the same list becomes [1, 2, 3].

20. Sorting low to high

Worked example

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

Line 2: sort() reorders in place

Why: Smallest to largest: the same list becomes [1, 2, 3].

Trace the list

Why: Verified by execution: prints [1, 2, 3].

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

21. Inspect it line by line: Sorting low to high

Error analysis

Annotate

Walk the callouts on Sorting low to high. Each one is a place this is easy to get subtly wrong.

  • Smallest to largest: the same list becomes [1, 2, 3].
  • Verified by execution: prints [1, 2, 3].

22. High-to-low with reverse=True

Concept

For a high-score board you want the biggest first. nums.sort(reverse=True) orders the list from largest to smallest, still in place.

23. Restore the missing line: Sorting high to low

Fill the middle

Fill in the blanks

From Sorting high to low — one line has had its right-hand side removed. Put it back.

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

Why: nums is what everything below it consumes, so the wrong expression here fails later and somewhere else. Verified by execution: prints [3, 2, 1].

24. Sorting high to low

Worked example

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

reverse=True flips the order to largest-first

Why: Verified by execution: prints [3, 2, 1].

stepcodenums now
1nums = [3, 1, 2][3, 1, 2]
2nums.sort(reverse=True)[3, 2, 1]
3print(nums)[3, 2, 1]

25. sort() works on text too

Concept

sort() also orders strings - alphabetically, A to Z. So "apple" comes before "banana". Same method, same in-place behavior.

26. Sorting words

Worked example

words = ["banana", "apple", "cherry"]
words.sort()
print(words)

sort() puts the words in alphabetical order

Why: Verified by execution: ['apple', 'banana', 'cherry'].

stepwords now
before sort()["banana", "apple", "cherry"]
after sort()["apple", "banana", "cherry"]

27. Something is wrong here: you can't sort mixed types

Anomaly

Predict first

A student writes this, and it looks reasonable:

A list with numbers AND text in it.

It is wrong. Say what breaks — and say it before you turn the page.

Correct: sort() works by checking which item is smaller.

Keep a list all one type. Sort numbers with numbers, words with words.

Why: sort() works by checking which item is smaller. It has no rule for "a" versus 1, so it stops with an error.

28. Trap: you can't sort mixed types

Trap

The trap

A list with numbers AND text in it.

mixed = [1, "a", 2]
mixed.sort()

Python can't compare a str and an int

Why: sort() works by checking which item is smaller. It has no rule for "a" versus 1, so it stops with an error.

expressionresult
[1, "a", 2].sort()TypeError: '<' not supported between instances of 'str' and 'int'

The fix

Keep a list all one type. Sort numbers with numbers, words with words.

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

All ints compare cleanly

Why: Verified by execution: [1, 2, 3]. A high-score board is all numbers, so you are safe.

expressionvalue
nums[1, 2, 3]

29. Break it on purpose: you can't sort mixed types

Break the constraint

Discussion prompt

The rule this trap just fixed:

Verified by execution: [1, 2, 3]. A high-score board is all numbers, so you are safe.

Now break it on purpose. Build a case that violates it and follow the consequences until something visibly fails. Where does the failure first show up — and would you have noticed it if you had not been looking?

Hint: The dangerous rules are the ones whose violation still produces an answer. If yours fails loudly, try to find one that fails quietly.

Answer:

sort() works by checking which item is smaller. It has no rule for "a" versus 1, so it stops with an error.

30. len(): count the items

Concept

len(nums) hands back the number of items in the list.

Unlike append and sort, len() does not change the list - it gives you a count you can store, print, or do math with.

31. len() in action

Worked example

print(len([3, 1, 2, 4]))
print(len([]))
print(len("robot"))

len counts the items

Why: A four-item list gives 4; an empty list gives 0.

len also counts the characters in a string

Why: Verified by execution: len("robot") is 5 - same idea, how many pieces are inside.

expressionvaluemeaning
len([3, 1, 2, 4])4four items
len([])0empty list
len("robot")5five characters

32. Inspect it line by line: len() in action

Error analysis

Annotate

Walk the callouts on len() in action. Each one is a place this is easy to get subtly wrong.

  • A four-item list gives 4; an empty list gives 0.
  • Verified by execution: len("robot") is 5 - same idea, how many pieces are inside.

33. The rule that ties it together

Concept

Methods that change the list in place - append, sort - hand back None, the "nothing" value, because the result already happened to your list.

len() is different: it computes a number and gives it back. So you write count = len(nums), but you never write nums = nums.sort().

34. "Do something" vs "give something"

Intuition

append() and sort() are do-something tools: they act on your list and return nothing (None). len() is a give-something tool: it returns a value for you to keep.

One question settles every case: did the tool change the list, or compute an answer about it? Change it - use it on its own line. Compute - capture what it returns.

35. Teach it back: "Do something" vs "give something"

Explain it

Discussion prompt

Explain "Do something" vs "give something" to a student a year behind you. No notation, no jargon they have not met — and it still has to be true.

Hint: If your explanation needs a symbol they have never seen, you are describing the notation rather than the idea.

Answer:

append() and sort() are do-something tools: they act on your list and return nothing (None). len() is a give-something tool: it returns a value for you to keep.

36. Restore the missing line: Proof: append and sort return None

Fill the middle

Fill in the blanks

From Proof: append and sort return None — one line has had its right-hand side removed. Put it back.

nums = [3, 1, 2]
print(nums.append(4))
print(nums.sort())
print(len(nums))

Why: nums is what everything below it consumes, so the wrong expression here fails later and somewhere else. append and sort do their job on nums, but the call evaluates to None - so that is what prints.

37. Proof: append and sort return None

Worked example

nums = [3, 1, 2]
print(nums.append(4))
print(nums.sort())
print(len(nums))

Printing the calls themselves shows None

Why: append and sort do their job on nums, but the call evaluates to None - so that is what prints.

len prints a real number

Why: Verified by execution: None, None, 4. len returns a value; the other two return None.

callprintswhy
nums.append(4)Nonechanged the list in place
nums.sort()Nonereordered the list in place
len(nums)4returns a count

38. Fill in: why for Proof: append and sort return None

Comparison

Comparison matrix

From Proof: append and sort return None: refill the why column from what you know. The rest of the table is as it appeared.

callprintswhy
nums.append(4)Nonechanged the list in place
nums.sort()Nonereordered the list in place
len(nums)4returns a count

39. Something is wrong here: nums = nums.sort() wipes your data

Anomaly

Predict first

A student writes this, and it looks reasonable:

You want nums sorted, so you "save" the result.

It is wrong. Say what breaks — and say it before you turn the page.

Correct: Your sorted list is thrown away.

Call sort() on its own line. It already changes nums - don't assign it.

Why: Your sorted list is thrown away. nums is now None, not a list - your data is gone.

40. Trap: nums = nums.sort() wipes your data

Trap

The trap

You want nums sorted, so you "save" the result.

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

sort() returned None, and you stored None into nums

Why: Your sorted list is thrown away. nums is now None, not a list - your data is gone.

expressionvaluetype
numsNoneNoneType

The fix

Call sort() on its own line. It already changes nums - don't assign it.

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

Let it mutate in place - no assignment

Why: nums is [1, 2, 3]. Same rule for append: write nums.append(x) on its own line, never x = nums.append(...).

expressionvaluetype
nums[1, 2, 3]list

41. Which of these survive contact with List Methods: append, sort, len?

Two truths and a lie

Sort into buckets

Some of these hold up and some are the exact mistakes this lesson is built to prevent. Sort them.

Holds up
A list holds many values in order, inside square brackets: [3, 1, 2]. Each item has a position, and the list can grow while your program runs.; Some list tools change the list itself - they add to it or rearrange it without making a new copy. That is called changing it in place.; nums.append(x) sticks x onto the end of nums, making the list one longer. It changes nums in place.
Breaks
Goal: add 3 and 4 onto [1, 2].; A list with numbers AND text in it.
sound
These are stated as this lesson states them — each one survives the edge cases List Methods: append, sort, len puts it through.
flawed
Each of these is lifted from a trap in this deck: reasonable-sounding, and wrong in a way that only shows up once you rely on it.

42. append vs +: change one, or make a new one

Concept

Two ways to grow a list, with a key difference. nums.append(x) changes nums in place (and returns None). nums + [x] builds a brand-new list and leaves nums alone - so you must store it.

Use append when you are piling items onto one list over time - like readings or scores.

43. By analogy: append vs +: change one, or make a new one

Analogy

Discussion prompt

Explain append vs +: change one, or make a new one by analogy to something with no Python in it at all — a queue, a recipe, a map, a bank balance, whatever fits. Then say where your analogy breaks.

Hint: An analogy that never breaks is not an analogy, it is the same idea wearing a hat. Find the seam — that is the part that is actually new.

Answer:

Two ways to grow a list, with a key difference. nums.append(x) changes nums in place (and returns None). nums + [x] builds a brand-new list and leaves nums alone - so you must store it.

44. Restore the missing line: append vs +

Fill the middle

Fill in the blanks

From append vs + — one line has had its right-hand side removed. Put it back.

a = [1, 2]
a.append(3)
print(a)
b = [1, 2] + [3]
print(b)

Why: b is what everything below it consumes, so the wrong expression here fails later and somewhere else. Verified by execution: a.append(3) changes a in place; [1, 2] + [3] makes a new list stored in b.

45. append vs +

Worked example

a = [1, 2]
a.append(3)
print(a)
b = [1, 2] + [3]
print(b)

Both end up [1, 2, 3], but the mechanism differs

Why: Verified by execution: a.append(3) changes a in place; [1, 2] + [3] makes a new list stored in b. The original [1, 2] in the + version is untouched.

linewhat it doesresult
a.append(3)changes a in placea is [1, 2, 3]
[1, 2] + [3]builds a new listb is [1, 2, 3]

46. Slicing: take the first few

Concept

A slice copies part of a list. nums[:3] gives the first three items as a new list.

Combine it with a high-to-low sort and nums[:3] is your top three - exactly the stretch goal for the board.

47. Break it if you can: Slicing: take the first few

Counterexample

Discussion prompt

A slice copies part of a list. nums[:3] gives the first three items as a new list.

That is stated as though it always holds. Do one of two things: produce a case where it fails, or say precisely what rules such a case out. "It just does" is not on the menu.

Hint: Hunt at the extremes first — zero, one, negative, empty, equal. If every extreme survives, the reason they survive is the proof.

Answer:

Combine it with a high-to-low sort and nums[:3] is your top three - exactly the stretch goal for the board.

48. Taking the top three

Worked example

scores = [90, 80, 70, 60, 50]
print(scores[:3])

scores[:3] copies the first three items

Why: Verified by execution: [90, 80, 70]. Because the list is already sorted high-to-low, those three are the podium.

expressionvalue
scores[:3][90, 80, 70]
scores[:1][90]

49. The in-place method recipe

Pattern

1. Build with append on its own line

Why: scores.append(x) adds one item in place. Never store what append returns - it is None.

2. Order with sort on its own line

Why: scores.sort() is low-to-high; scores.sort(reverse=True) is high-to-low. Never store what sort returns - also None.

3. Count with len and KEEP the result

Why: n = len(scores). len gives back a value, so capture it.

4. Ask: change the list, or compute about it?

Why: Change it (append/sort) -> own line. Compute about it (len) -> capture the return value.

5. Keep a list one type

Why: All numbers, or all words - so sort() can compare the items without a TypeError.

50. Where this shows up: List Methods: append, sort, len

Real world

Discussion prompt

Outside this lesson: where does List Methods: append, sort, len actually turn up? Name one concrete situation — a job, a piece of software someone ships, a decision somebody has to make — and say which part of The in-place method recipe is doing the work in it.

Hint: Vague is the failure mode here. "Engineering" is not a situation; "deciding whether this build is fast enough to ship" is.

Answer:

Pre-COSMOS Day 4 (Cluster 10: Robot Inventors), in depth. Growing a list with append(), ordering it with sort() and sort(reverse=True), counting with len(), and the big idea that in-place methods return None - so nums = nums.sort() wipes your data.

51. What has to happen first: Build it (1/4): start empty, append five scores

Ranking

Put in order

Put the moves of Build it (1/4): start empty, append five scores into the order they have to happen.

  1. Line 1: start from an empty list
  2. Lines 2-6: each append adds one score to the end
  3. Trace the list as it grows

Why: These are the moves of the worked example in the order it makes them, and each one is set up by the one before it. scores is [] - length 0. Every game will append onto it.

52. Build it (1/4): start empty, append five scores

Worked example

The High-Score Board. Start with nothing and append each game's score.

scores = []
scores.append(50)
scores.append(90)
scores.append(70)
scores.append(60)
scores.append(80)
print(scores)
print(len(scores))

Line 1: start from an empty list

Why: scores is [] - length 0. Every game will append onto it.

Lines 2-6: each append adds one score to the end

Why: The list grows by one item each time, in place - no new lists, no assignments.

Trace the list as it grows

Why: Verified by execution: prints [50, 90, 70, 60, 80] and 5.

afterscoreslen
start[]0
append(50)[50]1
append(90)[50, 90]2
append(70)[50, 90, 70]3
append(60)[50, 90, 70, 60]4
append(80)[50, 90, 70, 60, 80]5

53. Where the cost goes: Build it (1/4): start empty, append five scores

Cost model

Annotate

In Build it (1/4): start empty, append five scores, before reading the notes: mark where the time actually goes. Which line dominates?

  • scores is [] - length 0. Every game will append onto it.
  • The list grows by one item each time, in place - no new lists, no assignments.
  • Verified by execution: prints [50, 90, 70, 60, 80] and 5.

54. Predict the next row: Build it (2/4): sort the board high to low

Pattern

Predict first

The table runs: 1 | scores = [50, 90, 70, 60, 80] | [50, 90, 70, 60, 80] · 2 | scores.sort(reverse=True) | [90, 80, 70, 60, 50]

In Build it (2/4): sort the board high to low, given the rows so far: what is the next one — the row where step is 3?

Correct: 3 | print(scores) | [90, 80, 70, 60, 50]

stepcodescores now
1scores = [50, 90, 70, 60, 80][50, 90, 70, 60, 80]
2scores.sort(reverse=True)[90, 80, 70, 60, 50]
3print(scores)[90, 80, 70, 60, 50]

Why: The relationship between the columns, not the individual numbers, is what generates the next row. Verified by execution: [90, 80, 70, 60, 50] - in place, on its own line.

55. Build it (2/4): sort the board high to low

Worked example

scores = [50, 90, 70, 60, 80]
scores.sort(reverse=True)
print(scores)

sort(reverse=True) ranks the scores, best first

Why: Verified by execution: [90, 80, 70, 60, 50] - in place, on its own line.

stepcodescores now
1scores = [50, 90, 70, 60, 80][50, 90, 70, 60, 80]
2scores.sort(reverse=True)[90, 80, 70, 60, 50]
3print(scores)[90, 80, 70, 60, 50]

56. Guess the shape of the answer: Build it (3/4): the ranked board with len

Estimation

Predict first

Put it together: sort high-to-low, then announce how many games with len and the winner with scores[0].

Commit before you compute: what does Build it (3/4): the ranked board with len come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.

Correct: Sort first, then read from the ordered list

Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. After sorting, scores[0] is the highest.

57. Build it (3/4): the ranked board with len

Worked example

Put it together: sort high-to-low, then announce how many games with len and the winner with scores[0].

scores = [50, 90, 70, 60, 80]
scores.sort(reverse=True)
print("Games played:", len(scores))
print("Top score:", scores[0])
print(scores)

Sort first, then read from the ordered list

Why: After sorting, scores[0] is the highest. len(scores) counts the games. Verified by execution.

lineprints
print("Games played:", len(scores))Games played: 5
print("Top score:", scores[0])Top score: 90
print(scores)[90, 80, 70, 60, 50]

58. Work backwards from the answer: Build it (3/4): the ranked board with len

Reverse engineer

Discussion prompt

Work backwards. The example finished here:

Sort first, then read from the ordered list

What was it asked to do, and what must it have been given? Reconstruct the problem from its answer.

Hint: Every quantity in the result had to enter somewhere. Account for each one.

Answer:

Put it together: sort high-to-low, then announce how many games with len and the winner with scores[0].

59. Guess the shape of the answer: Build it (4/4): stretch - top three only

Estimation

Predict first

Stretch goal: print only the podium. Sort high-to-low, then slice the first three.

Commit before you compute: what does Build it (4/4): stretch - top three only come out to? A rough magnitude and the right form is enough — the point is to have something concrete to be wrong about.

Correct: Slice after sorting to grab the best three

Why: A prediction you can defend turns the computation into a check rather than a leap of faith — and an answer that contradicts it is caught on the spot. Verified by execution: scores[:3] is [90, 80, 70], printed as Podium: [90, 80, 70].

60. Build it (4/4): stretch - top three only

Worked example

Stretch goal: print only the podium. Sort high-to-low, then slice the first three.

scores = [50, 90, 70, 60, 80]
scores.sort(reverse=True)
top3 = scores[:3]
print("Podium:", top3)

Slice after sorting to grab the best three

Why: Verified by execution: scores[:3] is [90, 80, 70], printed as Podium: [90, 80, 70].

stepvalue
scores after sort[90, 80, 70, 60, 50]
scores[:3][90, 80, 70]
printedPodium: [90, 80, 70]

61. What each one costs: Build it (4/4): stretch - top three only

Trade off

Comparison matrix

From Build it (4/4): stretch - top three only: every row here is a choice with a cost. Fill the value column, then say which row you would actually pick and what you give up for it.

stepvalue
scores after sort[90, 80, 70, 60, 50]
scores[:3][90, 80, 70]
printedPodium: [90, 80, 70]

62. Check yourself: where does append add?

Check

Trace the list, then choose.

nums = [5, 2]
nums.append(8)
print(nums)
expressionvalue
nums?

Check your understanding

What does this print?

  • A. [5, 2, 8] (correct)
  • B. [8, 5, 2]
  • C. [5, 2, [8]]
  • D. [5, 10]

Answer: A

Why: append adds its argument as one item at the END of the list, in place. So nums becomes [5, 2, 8]. Verified by execution.

Why B tempts people
append always adds to the end, never the front. To put 8 at the front you would use nums.insert(0, 8).
Why C tempts people
append(8) adds the number 8, not a list [8]. You only see inner brackets if you append a list, like append([8]).
Why D tempts people
append adds a separate item; it does not add 8 onto the last number. The list gets one item longer, values never merge.

63. Check yourself: the None trap

Check

Watch the assignment on line 2 carefully.

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

Check your understanding

What does this print?

  • A. None (correct)
  • B. [1, 2, 3]
  • C. [3, 1, 2]
  • D. [3, 2, 1]

Answer: A

Why: sort() reorders the list in place and returns None. Storing that None into nums throws the list away, so nums is None and print shows None. Fix it by calling nums.sort() on its own line. Verified by execution.

Why B tempts people
This is what you wanted, but sort() returns None, not the sorted list. The assignment nums = nums.sort() overwrites your list with None.
Why C tempts people
The original list is gone too - the assignment replaced nums entirely with sort()'s return value, which is None.
Why D tempts people
Plain sort() is low-to-high, not reverse - but more importantly the result here is None because of the assignment, not any list at all.

64. Fill in: nums for Check yourself: the None trap

Comparison

Comparison matrix

From Check yourself: the None trap: refill the nums column from what you know. The rest of the table is as it appeared.

stepnums
1?
2?

65. Check yourself: appending a whole list

Check

Remember what append does with a list argument.

data = [1, 2, 3]
data.append([4, 5])
print(len(data))
expressionvalue
len(data)?

Check your understanding

What does len(data) print?

  • A. 4 (correct)
  • B. 5
  • C. 3
  • D. 2

Answer: A

Why: append adds the whole list [4, 5] as ONE item, so data is [1, 2, 3, [4, 5]] - four items. len counts top-level items, not the numbers inside the nested list. Verified by execution.

Why B tempts people
Assumed [4, 5] merged in to give [1, 2, 3, 4, 5]. append adds it as a single nested item, so the length is 4, not 5.
Why C tempts people
Forgot that append added anything. It always adds exactly one item, taking the count from 3 up to 4.
Why D tempts people
Undercounted the original items - data already held 1, 2, 3 before the append.

66. Check yourself: sort high to low

Check

Note the reverse=True.

nums = [4, 1, 7, 3]
nums.sort(reverse=True)
print(nums)
expressionvalue
nums?

Check your understanding

What does this print?

  • A. [7, 4, 3, 1] (correct)
  • B. [1, 3, 4, 7]
  • C. [4, 1, 7, 3]
  • D. [7, 1, 4, 3]

Answer: A

Why: sort(reverse=True) orders the list from largest to smallest, in place: [7, 4, 3, 1]. Verified by execution.

Why B tempts people
That is plain sort() order, low-to-high. reverse=True flips it to high-to-low.
Why C tempts people
sort() changes the list in place, so nums really is reordered even though sort() itself returns None. print(nums) shows the sorted list.
Why D tempts people
sort fully orders the list; it does not partially shuffle. The correct high-to-low order is [7, 4, 3, 1].

67. Check yourself: counting a built list

Check

How many items end up in the list?

scores = []
scores.append(80)
scores.append(95)
scores.append(60)
print(len(scores))
afterlen
all three appends?

Check your understanding

What does len(scores) print?

  • A. 3 (correct)
  • B. 0
  • C. 235
  • D. 1

Answer: A

Why: Three appends add three items to the empty list, so it holds [80, 95, 60] and len is 3. len counts how many items there are, not their total. Verified by execution.

Why B tempts people
scores started empty, but each append adds one item in place. After three appends it holds 3 items, not 0.
Why C tempts people
Added the score values (80 + 95 + 60 = 235). len counts how many items there are - 3 - not their sum.
Why D tempts people
Counted only one append. All three lines run, each adding an item, so the final count is 3.

68. Connect it up: List Methods: append, sort, len

Connect it up

Draw it

One page, no notation unless you need it: draw how these connect — The in-place method recipe · A list is an ordered collection · The big idea: changing a list "in place" · Your list is a whiteboard, not a photocopy · append(): add one item to the end. Put an arrow wherever one of them is what makes another possible, and label the arrow with why.

69. What you can do now

Recap

append() adds one item in place; sort() reorders in place; both return None, so call them on their own line. len() returns a count you can keep.

You wantWriteResult
add a scorescores.append(90)one item added, in place
order high-to-lowscores.sort(reverse=True)list reordered, in place
count the gamesn = len(scores)n holds the number
WRONG: save sort's resultscores = scores.sort()scores becomes None - data lost
top threescores[:3]first three after sorting

The one rule to remember: if a method changes the list, use it on its own line; if it computes something (like len), keep what it returns. Now go build the high-score board.

Sources

  1. Python 3 Tutorial - Data Structures (list methods, sort, len)
  2. Python 3 Library Reference - list.sort and sorted
  3. All snippets executed under CPython 3.12; outputs and error messages copied from real runs. — Author verification run, 2026-06-16 (Pre-COSMOS Prep Plan, Day 4).

Want this taught 1-on-1? Alexander tutors Python — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108