List copy() Method in Python

Python List copy() Method

In Python, the copy() method is used to create a shallow copy of a list. It is a built-in method available for lists in Python.

Here's the basic syntax of the copy() method:

new_list = list_name.copy()
  • new_list: This is the new list that will be created as a copy of the original list.
  • list_name: This is the name of the list that you want to copy.

It's important to understand the difference between a shallow copy and a deep copy:

  • Shallow Copy: A shallow copy creates a new list, but it only copies the references of the elements from the original list to the new list. If the original list contains mutable objects (e.g., other lists or dictionaries), the new list will still refer to those same objects in memory. Any changes made to the objects within the new list will also affect the original list and vice versa.

  • Deep Copy: A deep copy, on the other hand, creates a new list and recursively copies all the elements and their contents from the original list to the new list. As a result, the new list and the original list are completely independent of each other, and changes made to one list will not affect the other.

Let's see an example of using the copy() method to create a shallow copy:Example:

# Create the original list
original_list = [1, 2, 3, [4, 5]]

# Create a shallow copy of the original list
shallow_copy_list = original_list.copy()

# Modify an element in the shallow copy list
shallow_copy_list[0] = 100

# Modify an element in the nested list of the shallow copy list
shallow_copy_list[3][0] = 400

# Print both lists to see the result
print("Original List:", original_list)        # Output: [1, 2, 3, [400, 5]]
print("Shallow Copy List:", shallow_copy_list) # Output: [100, 2, 3, [400, 5]]

As you can see, changing an element in the shallow copy list affects the original list, and modifying an element in the nested list within the shallow copy list also affects the original list. This behavior is because the shallow copy only copies the references to nested objects, not the objects themselves.

If you need a completely independent copy that does not affect the original list or vice versa, you should consider using a deep copy. In Python, you can create a deep copy using the copy module's deepcopy() function.