10.13. Repetition and References¶
We have already seen the repetition operator working on strings as well as lists. For example,
origlist = [45, 76, 34, 55]
print(origlist * 3)
(repref1)
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.
origlist = [45, 76, 34, 55]
print(origlist * 3)
newlist = [origlist] * 3
print(newlist)
(repref2)
newlist
is a list of three references to origlist
that were created by the repetition operator. The reference diagram is shown below.

Now, what happens if we modify a value in origlist
.
origlist = [45, 76, 34, 55]
newlist = [origlist] * 3
print(newlist)
origlist[1] = 99
print(newlist)
(repref3)
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
.

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
.
Python 2.7
Step 1 of 5 line that has just executed next line to execute |
| |||||||||||||||||||||
(reprefstep)
Check your understanding
list-13-1: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = alist * 2
blist[3] = 999
print(alist)
list-13-2: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = [alist] * 2
alist[3] = 999
print(blist)