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:

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

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.
  • you can use the list() built in function
  • you can use the copy() function from the copy module. This is slower than the previous methods though.
  • finally, if items of the list are objects themselves, you should use a deep copy (see example below):
  • To convince yourself about the interest of the latter method, consider this list:

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

    This entry was posted in Python and tagged , . Bookmark the permalink.

    Leave a Reply

    Your email address will not be published.