Skip to main content

Foundations of Python Programming: Functions First

Section 9.6 Cloning Lists

If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of the word copy.
The easiest way to clone a list is to use the slice operator.
Taking any slice of a creates a new list. In this case the slice happens to consist of the whole list.
Now we are free to make changes to b without worrying about a. Again, we can clearly see in codelens that a and b are entirely different list objects.
Check your understanding

Checkpoint 9.6.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,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.
You have attempted of activities on this page.