Python: how to copy a list

To explain how to create a copy of a list, let us first create a list. We will use a simple list of 4 items:

list1 = [1, 2, "a", "b"]

Why do we want to create a copy anyway ? Well, because in Python, this assignement creates a reference (not a new independent variable):

list2 = list1

To convince yourself, change the first item of list2 and then check the content of list1, you should see that the two lists have been modified and contain the same items.

So, to actually copy a list, you have several possibilities. From the simplest to the most complex:

  • you can slice the list.
    list2 = 1ist1[:]
  • you can use the list() built in function
    list2 = list(1ist1)
  • you can use the copy() function from the copy module. This is slower than the previous methods though.
    import copy
    list2 = copy.copy(list1)
  • finally, if items of the list are objects themselves, you should use a deep copy (see example below):
    import copy
    list2 = copy.deepcopy(list1)
  • To convince yourself about the interest of the latter method, consider this list:

    import copy
    list1 = [1, 2, [3, 4]]
    list2 = copy.copy(list1)
    list2[2][1] = 40

    you should see that changing list2, you also changed list1. If this is not the intended behviour, you should consider using the deepcopy.

    Please follow and like us:
    This entry was posted in Python and tagged , . Bookmark the permalink.

    2 Responses to Python: how to copy a list

    Leave a Reply

    Your email address will not be published. Required fields are marked *