Lesson 05-04: Value Representation of Lists

Learning Target: I can understand the value representation of a list.

Stored by Reference

Let’s take the following program as an example:

And now let’s step through the codelens for that code:


You’ll notice that the variables list1 and list2 are pointing to the same thing, while string1 and string2 have individual (but identical) values!

That’s because list variables don’t store the data from the list itself - instead, they store the location of the data within the memory, often called the reference. We can see the actual location by using the id() function:

Notice how the IDs of a_list and same_ref are identical, because they’re both pointing to the same object, but new_list was created with its own set of (identical) values, but has a different ID.

Why does it matter?

This comes into play whenever you want to modify a list with functions.

We wrote a function double_list that takes in a list as an argument, doubles all the values, then returns the new list - except there is no new list - this function is modifying the original list - the one that exists outside the function! This is an issue when we want to make modifications to the list without changing the original list. In the next lesson, we will explore different methods of copying lists.

Checks for Understanding


    u0504-1: What built-in python function do you use to find the memory location of a variable?
  • (A) len()
  • (B) id()
  • (C) mem()
  • (D) ref()
Next Section - Lesson 05-05: Duplicating Lists