1.2.22 · D5Introduction to Programming (Python)

Question bank — List methods — append, insert, remove, pop, sort, reverse, count, index

1,288 words6 min readBack to topic

Parent: 1.2.22 List methods. Prereqs used: Lists — creation and indexing, Exceptions — ValueError and IndexError.


True or false — justify

True or False: lst.append(x) gives you back the new, longer list.
False. append mutates in place and returns ==None==; the longer list is lst itself, not a returned value — see Mutability vs Immutability in Python.
True or False: sorted(lst) and lst.sort() do the same thing.
False. sorted(lst) builds and returns a new list leaving lst untouched; lst.sort() reorders in place and returns None — full contrast in sorted() vs list.sort().
True or False: reverse() sorts the list into descending order.
False. reverse() only flips the current arrangement; if the list was unsorted it stays unsorted, just mirrored — sort first to get true descending.
True or False: pop() and remove() both hand you the deleted item.
False. Only pop returns the removed item; remove returns None — "pop pays you back, remove robs silently."
True or False: insert(0, x) and append(x) put x in the same place.
False. insert(0, x) puts x at the front (index 0, shifting everyone right); append(x) puts it at the end.
True or False: count(x) changes the list.
False. count is a query method — it only reads and returns a number, leaving the list unchanged.
True or False: You can call .sort() on a tuple.
False. Tuples are immutable, so they have no in-place methods like sort/append — see Tuples — why no append/sort.
True or False: lst.index(x) returns every position where x appears.
False. It returns only the index of the first occurrence; later duplicates are ignored.
True or False: After lst.sort(reverse=True) the list is reversed but not sorted.
False. reverse=True sorts into descending order — it is a true sort, not a flip of insertion order.

Spot the error

Spot the bug: result = names.sort(); print(result[0])
sort() returns None, so result is None and result[0] raises TypeError; call names.sort() as a statement, then index names[0].
Spot the bug: lst = [5, 6, 7]; lst.remove(0)
remove takes a value, so it searches for the value 0 (which isn't there) and raises ==ValueError==; to delete index 0 use lst.pop(0).
Spot the bug: nums = [4, 2]; biggest = nums.sort()[-1]
You cannot subscript the None that sort() returns; do nums.sort() then nums[-1], or use max(nums).
Spot the bug: data = [1, 'a', 2]; data.sort()
Python can't compare int with str using <, so this raises TypeError; keep list elements of one comparable type.
Spot the bug: q = [3,1,2]; q = q.append(9)
append returns None, so reassigning throws your list away and leaves q as None; just write q.append(9) with no assignment.
Spot the bug: colors.insert('red', 2)
The argument order is insert(index, value); here 'red' is being used as an index (a string), causing TypeError — it should be insert(2, 'red').
Spot the bug: while lst.count(0): lst.remove(0) on an empty list []
This is actually fine — count(0) on [] returns 0 (falsy), so the loop never runs; the trap is assuming it errors, but empty queries are safe.

Why questions

Why does append run fast but insert(0, x) run slow?
append drops the item in the next free end slot with no shifting; insert at the front must move every existing item one position right, so cost grows with length — see Time complexity — append O(1) vs insert O(n).
Why do mutating methods return None instead of the list?
To make the "I changed the original" intent explicit and prevent silent chaining bugs; if they returned the list you might forget the original was modified — the None forces you to notice mutation happened.
Why does remove take a value but pop take an index?
They answer different questions — remove means "delete this thing I found," pop means "delete whatever sits at this position"; matching the argument type to the question avoids ambiguity.
Why does 'apple' < 'banana' matter for sort()?
sort orders items by the < comparison; strings compare character-by-character by code point, which for lowercase letters matches alphabetical order — the same comparison logic explains Strings — index and count methods.
Why prefer sorted(lst) over lst.sort() sometimes?
When you need to keep the original order and have a sorted copy (e.g. displaying sorted while preserving input), sorted gives a new list without destroying the original.

Edge cases

Edge: what does [].pop() do?
Popping from an empty list raises ==IndexError== ("pop from empty list") because there is no last item to return — see Exceptions — ValueError and IndexError.
Edge: what does lst.index(x) do when x is absent?
It raises ValueError; unlike count (which safely returns 0), index has no "not found" number to give, so it errors.
Edge: pop(i) where i is out of range, e.g. [1,2].pop(5)?
Raises IndexError because there is no position 5; only the special no-argument pop() (meaning last) is always safe on a non-empty list.
Edge: negative index in pop — what does [10,20,30].pop(-1) return?
Returns 30, the last element, since -1 means "one from the end"; pop() with no argument is exactly pop(-1).
Edge: count(x) on an empty list?
Returns 0 — queries on empty lists are always safe and never raise, unlike removals which need something to act on.
Edge: remove(x) when x appears twice, e.g. [4,4,2].remove(4)?
Deletes only the first 4, giving [4, 2]; to delete all, loop with while x in lst: lst.remove(x).
Edge: insert(i, x) where i is far past the end, e.g. [1,2].insert(99, 9)?
No error — an out-of-range positive index for insert clamps to the end, so the result is [1, 2, 9] (unlike pop, which does error out of range).

Recall The two master keys to every trap above

Ask two questions of any list method call: Does it return the list, or None (or a value)? ::: Mutating methods return None; only pop/count/index return something useful. Does its argument mean a value or a position? ::: remove/count/index take values; insert/pop take index numbers.

Connections

  • 1.2.22 List methods
  • Mutability vs Immutability in Python
  • sorted() vs list.sort()
  • Tuples — why no append/sort
  • Time complexity — append O(1) vs insert O(n)
  • Strings — index and count methods
  • Exceptions — ValueError and IndexError
  • Lists — creation and indexing