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.
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
.
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
.
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
- [4, 2, 8, 999, 5, 4, 2, 8, 6, 5]
- print(alist) not print(blist)
- [4, 2, 8, 999, 5]
- blist is changed, not alist.
- [4, 2, 8, 6, 5]
- Yes, alist was unchanged by the assignment statement.
What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = alist * 2
blist[3] = 999
print(alist)
- [4, 2, 8, 999, 5, 4, 2, 8, 999, 5]
- [alist] * 2 creates a list containing two lists: alist repeated 2 times
- [[4, 2, 8, 999, 5], [4, 2, 8, 999, 5]]
- Yes, blist is a list containing two references to alist, so changes to alist appear in both.
- [4, 2, 8, 6, 5]
- print(blist)
- [[4, 2, 8, 999, 5], [4, 2, 8, 6, 5]]
- blist contains two references, both to alist, so changes to alist appear both times.
What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = [alist] * 2
alist[3] = 999
print(blist)