W3docs

How do I clone a list so that it doesn't change unexpectedly after assignment?

There are a few different ways to make a copy of a list in Python:

There are several ways to make a copy of a list in Python:

  1. Using the list.copy() method (Python 3.3+):

Using the .copy() method

python— editable, runs on the server
  1. Using the list() constructor:

Using the list() constructor

python— editable, runs on the server
  1. Using slicing:

Using list slicing

python— editable, runs on the server

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

  1. Using copy.copy():

Using copy.copy()

python— editable, runs on the server
  1. Using copy.deepcopy():

Using copy.deepcopy()

python— editable, runs on the server

Methods 1 through 4 create a shallow copy of the list, meaning that if the original list contains any mutable objects (like nested lists), changes to those objects will be reflected in both the original and the copy.

Method 5 creates a deep copy of the list, which means that the copy is completely independent of the original, including any mutable objects it contains.

Which method you use will depend on your specific needs. If you just want to create a new list with the same elements as the original, methods 1 through 4 will work. If you need to create a completely independent copy of the list, including any mutable objects it contains, you should use copy.deepcopy().