9. Repetition and References

We have already seen the repetition operator working on strings as well as lists. For example,

With a list, the repetition operator creates copies of the references. Although this may seem simple enough, when we allow a list to refer to another list, a subtle problem can arise.

Consider the following extension on the previous example.

new_list is a list of three references to orig_list that were created by the repetition operator. The reference diagram is shown below.

Repetition of a nested list

Now, what happens if we modify a value in orig_list.

new_list shows the change in three places. This can easily be seen by noting that in the reference diagram, there is only one orig_list, so any changes to it appear in all three references from new_list.

Same reference

Here is the same example in codelens. Step through the code paying particular attention to the result of executing the assignment statement orig_list[1] = 99.

(reprefstep)

It is worth noting that there is a difference between new_list = [orig_list] * 3 and an assignment statement where orig_list is not in brackets: another_list = orig_list * 3. The former creates a list of three references to orig_list whereas the latter creates a new object using the values in orig_list. Note in the example below how new_list will change when a value in orig_list changes, but another_list does not change because it is no longer bound to orig_list.

Check your understanding