Chapter 9 Lists
9.3 List Repetition¶
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 a list refers 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.
![Fig. 9.3 Repetition of a nested list.](../_images/fig9-3.jpg)
Fig. 9.3 Repetition of a nested list.¶
Now, what happens if a value in origlist
is modified?
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
.
![Fig. 9.4 Same reference.](../_images/fig9-4.jpg)
Fig. 9.4 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
.
Activity: CodeLens 4 (nine3Example1)
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. blist was a copy of the references in alist.
9.3Q-1: 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 alist repeated 2 times
- [[4, 2, 8, 999, 5], [4, 2, 8, 999, 5]]
- Yes, blist contains two references, both to alist.
- [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.
9.3Q-2: What is printed by the following statements?
alist = [4, 2, 8, 6, 5]
blist = [alist] * 2
alist[3] = 999
print(blist)
© Copyright 2024 GS Ng.