Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • use major list methods
  • explain in-place modification
  • avoid aliasing mistakes
  • distinguish sort() from sorted()

Major list methods

nums = [3, 1, 4]
nums.append(9)
nums.insert(1, 7)
nums.remove(4)
x = nums.pop()
print(nums, x)
Useful methods:
  • append(x)
  • extend(iterable)
  • insert(i, x)
  • remove(x)
  • pop([i])
  • sort()
  • reverse()
  • count(x)
  • index(x)

sort() vs sorted()

nums = [4, 2, 9]
nums.sort()
print(nums)
nums = [4, 2, 9]
new_nums = sorted(nums)
print(nums)
print(new_nums)

In-place trap

nums = [3, 1, 2]
x = nums.sort()
print(x)  # None

Aliasing trap

a = [1, 2, 3]
b = a
b[0] = 99
print(a)  # [99, 2, 3]
To copy list:
b = a[:]

Nested list example

matrix = [[1, 2], [3, 4]]
print(matrix[1][0])  # 3

Exam hints and traps

  • append adds one item
  • extend adds multiple items from iterable
  • remove(x) removes by value
  • pop(i) removes by index and returns item
  • sort() returns None

Quick practice

  1. Add 50 to end of [10, 20].
  2. Remove first occurrence of 3 from [3, 1, 3, 5].
  3. Predict:
a = [1, 2]
b = a
b.append(3)
print(a)

Answer key

  1. [1, 2, 3]