Stage 1 · Lesson 7 of 9
References, mutability and copying
In Python a variable holds a reference to an object. Think of it as a label stuck on a box, not a box with its own copy. After b = a where a is a list, both names point to the same list, so b.append(4) changes a too.
Sharing like this is called . Lists, dictionaries and sets are : they can change in place. Ints, floats, strings and are , so any "change" makes a new object.
That is why a that appends to a list parameter changes the caller's list, while one that adds 1 to an int parameter does not. Copy a list with list(a), a.copy() or a[:]. Remember that this is a shallow copy: for a list of lists, the inner lists are still shared. The next stage shows what this looks like in memory.
A question to check yourself, an AI practice session and 1 cheat sheet entry come when you add the roadmap to your account. Add it
Resources for this stage
Start with· follow one of these
- CoursePaidGrokking Python Fundamentals
Design Gurus · Beginner · $50
Beginner Python with an in-browser exercise after nearly every lesson
- CourseFreeCS50's Introduction to Programming with Python
Harvard University · Beginner
Free Harvard course whose weekly problem sets make you write real programs