# CS111 Lecture: Lists, Memory Diagrams, Mutable vs. Immutable Values¶

## 1. Review: You can use [ ] to make lists in python¶

A Python list is a sequence of values, which are called elements of the list. A list can be created by writing a sequence of comma-separated expressions delimited by square brackets.

Lists themselves are Python objects, and so can be named by variables.

Below are some homogenous lists, which means that all elements of the list have the same type.

Note: If an element is an expression, such as 1<2 or 3+4, it's first evaluated to a value, and then stored in the list.
So, can you guess what is stored in somebools, somenums, and somestrings?

## 2. Review: Indexing lists¶

To access individual elements of the list as opposed to the entire list, we use indices.

Very Important Note: The nonnegative indices always start at 0 and end at a number one less than the length of the list.

Accessing the first element of the list, using index 0:

What happens if you write primes[8]? Can you explain it?

Now that we reviewed how lists are created and indexed via Python code, let's discuss a model of how lists are stored in the computer memory.

## 3. Model: List Memory Diagrams¶

We draw lists with n elements as a big box containing n smaller boxes (slots) that hold the n elements. Each smaller box or slot is written with an index number above the box. Organizing lists with these diagrams help us understand ways to interact with lists.

Below are two examples of memory diagrams for two different lists. Each list is assigned to a variable. To depict a variable using memory diagrams we simply write the name of the variable and a box to the right. When the value of the variable is a list, we draw an arrow from the variable box to the big box representing the list.

For a length-n list, slots can also be addressed by indices that go (right to left) from -1 to -n.

## 4. Diagrams and Indexing with Nested Lists¶

Often, we will work with lists of lists (or nested lists). We can create and index them similarly to simple lists

We can assign list elements to new variables:

We just showed two different ways to refer to the same value, "raccoon".

## 6. You can mix and match different types within a list (heterogeneous lists)¶

Here's a heterogeneous list, containing several different types of elements.

For you: Try to predict the value for each of the following expressions:

## 7. Lists are sequences¶

### len: Length of a list¶

We will use the familiar built-in function len() to find the length of a list.

### List slicing¶

Use the slicing operator : to create a new list that contains some of the elements of the original list.

## 8. Lists are mutable¶

In this case mutation means:

• we can change the contents of the list slots
• we can change the structure of the list by adding and removing list slots. We will see three list methods for doing this: append, pop, and insert.

### pop examples¶

A method to remove items from a list.

Let's see first what's in the list myList, which was already mutated in the previous cells in this Notebook:

Notice that pop returns the value that it removed from the list.

Notice that when we don't use an argument for pop, by default it removes the very last element.

### insert examples¶

insert is a method that takes two parameters:

1. the index of the list slot where the insertion will hapen;
2. the value to be inserted

### Aliasing¶

Aliasing creates another variable name for the same object in Python. We can depict these with memory diagrams by simply drawing another box for the variable with the variable name on the left. The contents of the variable box will have an arrow pointing to that object.

#### Aliasing Example 1¶

Use memory diagrams to explain the the list structures that result from executing the following statements in order

The final list diagram is the one below. A key feature of this diagram is aliasing, which means that the same list objects can be accessed by different expressions involving variables and lists. For example, the expressions L1, L4[0], and L4[1] all refer to the same 2-element list object [7,4], while the expressions L2, L3, L4[2], and L4[3] all refer to the same 3-element list object [7,8,5]. Memory diagrams involving lists are essential for understanding aliasing, which is essential for understanding how operations that mutate lists will behave.

#### == tests for structural equality, but not aliasing¶

When used to compare two lists, Python's equality operator == returns True if and only if (1) the two list have the same length and (2) all the corresponding indices have values for which == returns True. This is called structural equality of lists.

As shown below, two lists can be structurally equal via == even if they are not aliases of the same lists. So == is too weak a test for determining aliases:

#### Python's built-in id function¶

Python's id() function returns a long number that is a unique identifier for each object in a memory diagram. You can think of it as being the abstract address of the object in memory. If two list expressions have the same id, they must be represented by a single list box in a memory diagram (i.e., they are aliases for the same list value). If two list expressions have different ids, they must be represented by two different list boxes in a memory diagram.

For example, id can tell us that L2b and L3b are aliases for the same list, but that L1b is a different list:

In our bigger running example, because L1, L4[0], and L4[1] are aliases of the same list, all return the same number using the id function:

Because L2, L3, L4[2], and L4[2] are aliases of a list that is different than L1, all share an id that is different that the id for L1:

For this reason, id is handy for reasoning about aliasing/sharing in memory diagrams.

#### Python's is operator¶

Python's binary is operator returns True if its two operands have the same id; otherwise it returns False. It is also very useful for reasoning about aliasing/sharing in memory diagrams.

In the small example, is shows that L2b and L3b are the same list, but they are different from L1b:

In the larger running example, it shows which expressions are aliases for the same lists:

#### Aliasing Example 2¶

As a second example of aliasing, consider modifications to the memory diagram at the end of the insert examples:

We begin by introducting the alias list2 for myList:

We also inroduce adamsList as an alias for list2[4]

Without a memory diagram, it's bit less obivous that adamsList is also an alias for myList[4]:

Now let's make myList[1] be an alias for myList[4]:

Finally, let's change adamsList[2] to be 'JQ':

Can you predict the printed represenation of list2 now? Without memory diagrams, this can be very challenging to predict!

It turns out that the list adamsList has four other aliases in this example:

This can be very challenging to understand without the aid of the final memory diagram for this example:

## 9. Pop Quiz¶

What is the value of c[0] at the end of executing the following statements? Draw a memory diagram to justify your answer!

Let's break down some of the code to see what is going on. Although a and b seem to have the same value, they occupy different addresses in the memory, so, they are not the same object.

In the list c, c[1] is an alias for a and c[2] is an alias for b, but they are not aliases for each other:

Because of aliasing, changing a slot in b changes the same slot in c[2], but not in a or c[1]:

Because c[1] is an alias for a, changing c[1][0] changes a[0] but does not affect b or c[2]:

Now we can determine the summands of a[0] + c[1][1] + b[0] + c[2][1]

Did you get the correct answer?

### Part 2 of Pop Quiz¶

The operator [:] creates a new list that is a copy of the list in a, so the ids are still different for a and b. So the results for this second scenario are exactly the same as for the first scenario.

### Part 3 of Pop Quiz¶

Since there is aliasing between a and b in this scenario, the final results are different from the previous two.

## 10. Tuples¶

A tuple is an immutable sequence of values. It's written using parens rather than brackets.

On tuples we can use any sequence operations that don't involve mutation:

However, any sequence operation that tries to change a tuple will fail

## 11. Tuple Assignment¶

Consider an information tuple with three parts: (1) name of class (2) number of students (3) fulfills MM

We can extract name parts of this tuple using three assignments:

But it's simpler to extract all three parts in one so-called tuple assignment:

Also note that parens are optional in a tuple assignment, so this works, too:

## 12. Optional: Enumerations¶

An enumeration pairs an index with each element of a sequence.

It's handy to loop over the (index, value) pairs in an enumeration.

The above shows that tuple assignment works for for loops, too!