Module 3 · Operations on lists · Lesson 1 of 5
Lists are references
Here's one feature of lists that surprises almost everyone — and it's worth memorising, because forgetting it causes bugs that are genuinely hard to track down. Look at this little program: it makes a one-element list list_1, assigns it to list_2, changes list_1, and prints list_2.
You'd expect list_2 to still be [1]. It isn't — it prints [2]. Watch why.
Lists (and most other complex Python values) are stored differently from ordinary scalar variables like numbers. The key idea:
- the name of an ordinary variable is the name of its content;
- the name of a list is the name of a memory location where the list is stored.
Read those two lines once more — the difference is everything. So list_2 = list_1 copies the name of the list, not its contents. Afterwards both names identify the same spot in memory: change one and you've changed the other, and vice versa. We call this an alias.
So how do you cope with it when you genuinely want a separate copy? Make one explicitly. The simplest way is a slice of the whole list, list_1[:], which builds a brand-new list with the same values. list(list_1) and list_1.copy() do the same thing.
That [:] trick is your first taste of slicing — and slicing turns out to be one of the most useful things you can do to a list. That's next.