loop
Operations on lists

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.

One list, two names
list_1list_2memory[1]

Lists (and most other complex Python values) are stored differently from ordinary scalar variables like numbers. The key idea:

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.

Run it yourselfruns in your browser · Python
main.py

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.

Run it yourselfruns in your browser · Python
main.py

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.