List Operations: Build and Modify
Mutating and Filtering Lists
Part of: Variables, Lists & Procedures
Reading a list is only half the story. Real programs grow, shrink, sort, and filter their data. Unlike strings, Python lists are mutable : you can change them in place. Adding and removing. - append(x) adds x to the end, the most common list operation. - insert(i, x) puts x at index i, shifting later elements right. - remove(x) deletes the first element equal to x. - pop() removes and returns the last element. Sorting and reordering. sort() changes the list itself and returns None, so never write nums = nums.sort(), that would store None. Filtering with a new list. Often you want a list derived from another: only the even numbers, or everything except a target. Build a fresh list as you traverse: Python also offers a list comprehension as a compact form of the same idea: Joining for output. To print a list of numbers as a space-separated line, convert each to a string and join: What usually goes wrong. What you see What caused it How to fix it --- --- --- Some copies of the target survive Only the first match was deleted, or items were removed from the same list that was being walked Build a separate list of survivors instead of deleting during the walk The list becomes None The re
Challenge: Remove All Occurrences