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

original_list = [1, 2, 3]
new_list = original_list.copy()
print(new_list)
  1. Using the list() constructor:

Using the list() constructor

original_list = [1, 2, 3]
new_list = list(original_list)
print(new_list)
  1. Using slicing:

Using list slicing

original_list = [1, 2, 3]
new_list = original_list[:]
print(new_list)

<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()

import copy
original_list = [1, 2, 3]
new_list = copy.copy(original_list)
print(new_list)
  1. Using copy.deepcopy():

Using copy.deepcopy()

import copy
original_list = [1, 2, 3]
new_list = copy.deepcopy(original_list)
print(new_list)

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().