Arrays · 2 / 23 Theory

Adding, removing and changing elements

Lists can grow and shrink while the program runs. These are the methods you will use most.

Adding

l = [1, 2, 3]
l.append(4)          # at the end          → [1, 2, 3, 4]
l.insert(0, 10)      # at a position       → [10, 1, 2, 3, 4]
l.extend([5, 6])     # several at the end  → [10, 1, 2, 3, 4, 5, 6]

append is by far the most important: it is the way to keep in a list the values read in a loop.

Removing

l = [10, 20, 30, 20]
l.remove(20)         # removes the first 20       → [10, 30, 20]
last = l.pop()       # removes and returns the last → 20, l = [10, 30]
first = l.pop(0)     # removes position 0         → 10, l = [30]
del l[0]             # deletes by position        → l = []

remove raises ValueError if the value is not there. pop on an empty list raises IndexError.

Finding a position and counting

l = [5, 3, 5, 8]
print(l.index(5))   # 0  (first position of 5)
print(l.count(5))   # 2  (how many times it appears)

Reversing and sorting

l = [3, 1, 2]
l.reverse()          # reverses in place → [2, 1, 3]
l.sort()             # sorts in place    → [1, 2, 3]
l.sort(reverse=True) # from largest to smallest → [3, 2, 1]

m = [3, 1, 2]
print(sorted(m))     # [1, 2, 3]  (new list)
print(m)             # [3, 1, 2]  (m does not change)

Careful: l.sort() and l.reverse() modify the list and return None. Writing l = l.sort() leaves l as None.

Copying a list

Assigning a list to another variable does not copy it: both variables point to the same list.

a = [1, 2, 3]
b = a            # same list
b.append(4)
print(a)         # [1, 2, 3, 4]  a changed too!

c = a.copy()     # independent copy (also a[:] or list(a))
c.append(5)
print(a)         # [1, 2, 3, 4]