Python list.copy() function


The list.copy() method in Python is used to create a shallow copy of a list. A shallow copy means that it creates a new list containing references to the original list's elements. This method allows you to create a duplicate of the list that can be modified independently of the original list.

Syntax

new_list = original_list.copy()

Return Value

  • The method returns a new list that is a shallow copy of the original list.

Example Usage

  1. Creating a Copy of a List:

    original_list = [1, 2, 3, 4] copied_list = original_list.copy() # Creates a copy of the original list print(copied_list) # Output: [1, 2, 3, 4]
  2. Modifying the Copied List: Changes made to the copied list do not affect the original list:

    original_list = [1, 2, 3] copied_list = original_list.copy() copied_list.append(4) # Modifying the copied list print(original_list) # Output: [1, 2, 3] (original list remains unchanged) print(copied_list) # Output: [1, 2, 3, 4] (copied list is modified)
  3. Shallow Copy Behavior: If the list contains mutable elements (like other lists), the copied list will still reference those mutable elements:

    original_list = [[1, 2], [3, 4]] copied_list = original_list.copy() copied_list[0][0] = 99 # Modifying a mutable element in the copied list print(original_list) # Output: [[99, 2], [3, 4]] (original list is affected) print(copied_list) # Output: [[99, 2], [3, 4]]
  4. Copying an Empty List: Copying an empty list also works without errors:

    empty_list = [] copied_empty = empty_list.copy() print(copied_empty) # Output: []
  5. Using the list() Constructor: You can also create a copy using the list() constructor, which gives the same result:

    original_list = [1, 2, 3] copied_list = list(original_list) # Creates a copy using list() print(copied_list) # Output: [1, 2, 3]

Summary

  • list.copy() creates a shallow copy of a list, allowing for independent modifications.
  • It does not affect the original list when changes are made to the copied list.
  • If the original list contains mutable elements, changes to those elements will be reflected in both lists since they are still referencing the same objects.
  • This method is a straightforward way to duplicate lists in Python without using slicing or the list() constructor.