TutreNews Learn

Lists

List methods and mutability

Goal: Add, remove and sort items and know which operations change the original · 11 min

Lists are mutable: you can change them after creating them. The most important methods:

methodeffectreturns
append(x)add x at the endNone
insert(i, x)insert x before index iNone
extend(other)add all items of another listNone
remove(x)delete the first x (ValueError if absent)None
pop() / pop(i)remove and return the last / i-th itemthe item
sort()sort in place (reverse=True for descending)None
reverse()reverse in placeNone
index(x) / count(x)position of the first x / number of xint

Important: methods that change the list in place return None. A common bug is numbers = numbers.sort(), which replaces the list with None. Use numbers.sort() alone, or sorted(numbers), which returns a new sorted list and leaves the original untouched.

a = [3, 1, 2]
b = sorted(a)   # b = [1, 2, 3], a unchanged
a.sort()        # a = [1, 2, 3]

Assignment does not copy a list. b = a makes both names point to the same list, so changing one changes the other. Make a real (shallow) copy with a.copy(), list(a) or a[:].

Worked example: A shopping list

  1. Start with items = ["milk", "eggs"].
  2. append("bread") adds at the end; insert(0, "tea") adds at the front.
  3. pop() removes and returns "bread"; remove("eggs") deletes by value.
items = ["milk", "eggs"]
items.append("bread")
items.insert(0, "tea")
print(items)
print(items.pop())
items.remove("eggs")
print(items)

Output:

['tea', 'milk', 'eggs', 'bread']
bread
['tea', 'milk']