smartyfy.mrindigi.com

Python Master Course V2 — 033. List Methods and Mutations

SMARTYFY ACADEMY · MODULE 04 · Collections and Data Modelling · LESSON 033 / 200

List Methods and Mutations

Study time: 70–100 minutes · Prerequisite: Lesson 032 and earlier Python collections lessons.

Video lesson

Video not yet available. Reserved area for a verified video link or embedded player. No video has been uploaded.

Learning outcomes

  • Understand the core concepts of list methods and mutations.
  • Predict outputs and explain data changes.
  • Choose appropriate data structures and validate inputs.
  • Apply the lesson to a practical Python project.
  • Identify common mistakes and test edge cases.

Understand the idea, then trace the code

Separate a method’s effect from its result

A list method can change the list, return a useful value, or do both. Most methods whose purpose is mutation return None. For example, append, extend, insert, remove, clear, reverse, and sort change the existing object. Assigning their return value back to the variable loses that variable’s reference to the list. By contrast, pop changes the list and returns the removed item, which makes it useful for processing a stack of pending work.

jobs = ["draft"]
result = jobs.append("review")
print(jobs)
print(result)
finished = jobs.pop()
print(finished, jobs)

Expected output

['draft', 'review']
None
review ['draft']

Trace this example in two columns: the current list and the returned value. Appending adds review to the same list but returns no new collection. Popping without an index removes the final element. The string review becomes the value of finished, while draft remains in jobs. Tracking these two effects separately prevents the common mistake of writing jobs = jobs.append(new_job).

Add one object or consume many objects

append(value) adds one object as one item, even if that object is itself a list. extend(iterable) adds each item from its argument separately. Extending with a string adds its individual characters, whereas appending a string adds one string. Use append for one complete record and extend for a batch of records. insert(index, value) places one item before a position; unlike single-item indexing, out-of-range insert positions are clipped to the beginning or end.

one = [1, 2]
one.append([3, 4])
many = [1, 2]
many.extend([3, 4])
print(one)
print(many)

Expected output

[1, 2, [3, 4]]
[1, 2, 3, 4]

Choose removal by value or by position

remove(value) deletes the first equal value and raises ValueError if none is present. pop(index) deletes a position and returns its item; an invalid index or an empty list raises IndexError. clear() removes every item and is safe on an empty list. reverse() reverses current order without comparing values; sort() orders comparable values. Neither returns a replacement list. Search methods such as index and count do not mutate: index finds the first matching position, while count reports how many matches exist. If the value is absent, index(value) raises ValueError, while count(value) returns zero.

State who owns the list

Assignment does not copy a list. If two variables name the same object, a mutation through either name is visible through both. A helper that should preserve the caller’s order can make a shallow copy first. That protects the outer list’s slots but does not detach nested objects. Document whether a helper edits its input or returns an updated list so the caller can choose the appropriate behavior.

def update_queue(queue, new_item, completed):
    result = queue.copy()
    if completed in result:
        result.remove(completed)
    result.append(new_item)
    return result

original = ["A", "A", "B"]
updated = update_queue(original, "C", "A")
print(original)
print(updated)

Expected output

['A', 'A', 'B']
['A', 'B', 'C']

Here completion removes one existing occurrence before the new job is appended. Duplicate names therefore represent separate queued entries. For unique real jobs, use unique identifiers rather than treating a repeated label as the same job. Avoid removing items from a list while traversing that same list: shifted positions can cause the next item to be skipped. Build a separate result or traverse a copy when removal is required.

Progressive runnable example

Setup: Python 3.10 or newer, standard library only. Save as lesson_033.py and run with python lesson_033.py or python3. The outputs below are expected, not claims of execution on the website.

a=[2,3]
a.append(4)
a.insert(0,1)
a.remove(3)
print(a)
print(a.pop())

Expected output:

[1, 2, 4]
4

Walkthrough: Read the starting values, identify each operation’s effect, and explain the resulting collection or return value. Change one input and predict the output before running the code again.

Real-world project — List Methods and Mutations application

Update a queue without changing its source. Completion removes the first matching existing job before a new job is appended. Test duplicate and identical labels; the ordering of these mutations is part of the contract.

def update_queue(queue, new_item, completed):
    result = queue.copy()
    if completed in result:
        result.remove(completed)
    result.append(new_item)
    return result

print(update_queue(["A", "B"], "C", "A"))
print(update_queue([], "A", "A"))

Expected output:

['B', 'C']
['A']

Optional later extension: After the file-handling lessons, extend this workflow to import validated CSV records. This is not required for the current lesson.

Testing checklist: Normal input, empty input, single item, duplicates, malformed values and large collections. Document which cases should raise errors and which should return a neutral result.

Common mistakes and professional practices

  • Assuming a nonempty collection without checking.
  • Accidentally mutating a shared list or nested object.
  • Confusing a method’s return value with its in-place effect.
  • Ignoring stable ordering or tie-breaking requirements.
  • Failing to validate data types and record fields.
  • Testing only the happy path rather than boundaries and failures.

Practice: predict, debug, and explain

Try each challenge before opening its answer. Write the result and explain the rule that produces it.

1. Predict values and side effects

Predict the three printed lines. Which method returns a list?

a = [4, 2]
r = a.reverse()
x = a.pop(0)
print(a)
print(r)
print(x)
Optional hint

Trace the list after reverse, then remove position zero. Keep method return values in a separate column.

Reveal answer and reasoning

Expected output

[4]
None
2

Reverse changes a to [2, 4] and returns None. Pop removes the item at position zero and returns 2. Neither method returns a list here.

2. Distinguish a word from its letters

Predict both lists.

a = []
b = []
a.append("go")
b.extend("go")
print(a)
print(b)
Reveal answer and reasoning

Expected output

['go']
['g', 'o']

Append takes one object. Extend iterates its input; a string yields one-character strings. To add several whole words, extend with a list of words.

3. Repair the lost reference

Why does this code fail on its final line? Give the smallest repair.

tasks = ["read"]
tasks = tasks.append("write")
print(len(tasks))
Reveal answer and reasoning

Append returns None, so tasks is rebound to None and len(tasks) raises TypeError. Call append as a statement, without assignment:

tasks = ["read"]
tasks.append("write")
print(len(tasks))

Expected output

2

4. Handle duplicate and missing values

Starting with ["A", "B", "A"], what remains after remove("A")? What happens if the next call is remove("C")?

Reveal answer and reasoning

The first call leaves ["B", "A"] because only the first equal item is removed. The second raises ValueError and leaves that list unchanged. If a missing item is normal, test membership before removing it; if it violates the contract, let a clearly explained error identify the problem.

5. Design a completion update

Why does the revised queue helper remove the completed item before appending the new one? Consider an empty queue where both labels are A.

Reveal answer and reasoning

Removing first limits completion to jobs already in the queue. The new A is then appended, producing ["A"]. Appending first and removing afterward would consume the just-added A, producing an empty queue. Ordering mutations expresses the intended business rule, so test identical labels explicitly.

Knowledge check

Use the five topic-specific challenges above as your knowledge check. Explain each answer before revealing its worked reasoning.

Return to practice questions ↑

Mastery checkpoint

Optional advanced challenge: Add validation, two extra features and five tests to the project. Keep new features within the lesson’s stated input and output contract, and explain the behavior of empty and invalid inputs.

Explain the data structure and operation, run the example, adapt the project and demonstrate at least three edge-case tests. Review the prerequisite lesson if you cannot predict the result.

Summary: List Methods and Mutations becomes reliable when paired with clear data models, validation and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.