Skip to main content

copy()

The copy() function in Python is a method for lists that creates a shallow copy of the list. It returns a new list with the same elements as the original list. This means that changes made to the new list will not affect the original list, but changes to any mutable elements within the list (e.g., lists or dictionaries) will affect both the original and copied list.

Parameter Values

This function does not accept any parameters.

Return Values

The copy() method of a list returns a new list, i.e., a shallow copy of the original list.

How to Use copy() in Python

Example 1:

The copy() method creates a shallow copy of a list. Changes made to the new list will not affect the original list.

original_list = [1, 2, 3]
new_list = original_list.copy()
new_list.append(4)
print(new_list)
# Output: [1, 2, 3, 4]
print(original_list)
# Output: [1, 2, 3]
Example 2:

Shallow copy means the copied list contains references to the original list's elements. Modifying a nested element will affect the original list.

original_list = [[1, 2], [3, 4]]
new_list = original_list.copy()
new_list[0][0] = 5
print(new_list)
# Output: [[5, 2], [3, 4]]
print(original_list)
# Output: [[5, 2], [3, 4]]
Example 3:

Using the copy() method is an effective way to create a duplicate of a list without impacting the original list during modifications.

original_list = ['a', 'b', 'c']
new_list = original_list.copy()
new_list.remove('b')
print(new_list)
# Output: ['a', 'c']
print(original_list)
# Output: ['a', 'b', 'c']