List Methods and Mutations
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Because lists are mutable, you can add, remove, and rearrange elements in place. Knowing which methods modify the list in place is vital.
Adding elements: append, insert, extend
Mutation is changing a list in place, without making a new list. Methods such as append, insert, extend, pop and remove mutate the list they are called on.
Use .append(x) to add to the end, .insert(i, x) to insert at an index, and .extend(iterable) to merge another list.
tasks = ["Design", "Code"]tasks.append("Test")tasks.extend(["Deploy", "Monitor"])print(tasks)Notice that tasks.append([1, 2]) would add a nested list as a single element, while .extend([1, 2]) unpacks and appends each item.
Removing elements: pop, remove, clear
Use .pop(index) to remove and return an item by index, or .remove(value) to delete the first occurrence of a value.
queue = ["user1", "user2", "user3"]served = queue.pop(0)print(f"Served: {served}")print(f"Remaining: {queue}")Calling .pop() without arguments removes and returns the last element in O(1) time (functioning as a stack).
In-place sort() versus sorted()
list.sort() sorts the list in place and returns None. The built-in sorted(list) returns a new sorted list, leaving the original unchanged.
nums = [40, 10, 30]sorted_copy = sorted(nums)print(f"Copy: {sorted_copy}")print(f"Original: {nums}")Example 1 · Updating a stock list
inventory = ["laptop", "mouse", "keyboard"]inventory.append("monitor")inventory.remove("mouse")inventory.sort()
print(inventory)['keyboard', 'laptop', 'monitor']
What this code does
- Appends 'monitor' to inventory.
- Removes 'mouse'.
- Sorts the remaining items alphabetically in place: ['keyboard', 'laptop', 'monitor'].
Example 2 · Ranking marks without changing the original
marks = [72, 95, 61, 88]ranked = sorted(marks, reverse=True)print(ranked)print(marks)print(95 in marks)print(marks.index(95))print(marks.count(61))[95, 88, 72, 61] [72, 95, 61, 88] True 1 1
What this code does
sorted()returns a new list, somarkskeeps its first order.inanswers True or False.index()gives the position of the first match.count()says how many times a value appears.
Do not write nums = nums.sort(), as that rebinds nums to None because .sort() modifies in place.
Aliasing versus copying
Alias is a second name for the same list. Writing b = a does not copy the list, so a change made through b also shows when you read a.
Assigning a list to another name gives that name the same list. To get a separate list, copy it with .copy() or [:].
cart = ["pen", "book"]backup = cartsaved = cart.copy()cart.append("bag")print(backup)print(saved)print(backup is cart)Example 3 · Two names, one list
team = ["Asha", "Ravi"]same_team = teamsame_team.append("Meera")print(team)print(team is same_team)snapshot = team[:]team.pop()print(snapshot)print(team)['Asha', 'Ravi', 'Meera'] True ['Asha', 'Ravi', 'Meera'] ['Asha', 'Ravi']
What this code does
appendthroughsame_teamchanges the one list that both names point to.team[:]makes a separate list, sosnapshotkeeps all three names afterpop()removes the last one fromteam.
backup is another name for the same list, so it shows "bag". saved is a new list made before the change, so it does not. is checks whether two names point to the same object.
Next step
Check your understanding
9 quick questions