10.13. 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.

newlist is a list of three references to origlist 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 origlist.

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

Same reference

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

(reprefstep)

Check your understanding

Next Section - 10.14. List Methods