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: Why it matters Filtering, sorting, and appending are the verbs of data processing. A search engine filters results, a leaderboard sorts scores, a shopping cart appends items. Mastering in-place mutation versus building a new list, and knowing which methods return None, keeps your data transformations correct.

Challenge: Remove All Occurrences