Skip to content
Python for Quantitative Finance / Built-In Data Structures

Lists and Mutability

Tuples and Ranges built an ordered sequence type that, once constructed, can never change. Lists are the mutable counterpart: syntactically almost identical (square brackets instead of parentheses), but changeable in place after creation. That one difference — mutability — has consequences that reach well beyond convenience: two names can end up referring to the same underlying list object (aliasing), and a list mutated while being iterated over can behave in ways that surprise even careful programmers. This note works through both, and closes with list comprehensions, a concise syntax for building a new list from an existing sequence.
Learning objectives. By the end of this note you should be able to:
  • construct, index, slice, and mutate lists using the standard list methods (append, extend, insert, remove, pop, sort, reverse);
  • distinguish assigning a variable to an existing list (creating an alias) from creating a genuinely independent copy (cloning), and predict when a mutation is visible through more than one name;
  • explain, using a hidden-loop-counter argument, why mutating a list while iterating over it produces surprising results, and apply the standard fix (iterate over a clone);
  • write a list comprehension, including a filtering if clause, and recognise when a comprehension helps readability versus when it hurts it.

In this lesson

  1. Lists: mutable ordered sequences
  2. Aliasing
  3. The standard list methods
  4. Cloning, and the loop-mutation trap
  5. List comprehensions

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.