Python List copy() Method
The copy() method in Python is used to create a shallow copy of a list. This means that the method creates a new list containing the same elements as the original list but maintains its own identity in memory. It’s useful when you want to ensure that changes to the new list do not affect the original list and vice versa.
Here’s is a basic example of coping a list using copy() method.
a = [1, 2, 3]
# Copy the list
b = a.copy()
print('a:', a)
print('b:', b)
Output
a: [1, 2, 3] b: [1, 2, 3]
Syntax of List copy() Method
Syntax: list.copy()
Parameters
The copy() method doesn’t take any parameters.Returns
Returns a shallow copy of a list.
Modifying the Copied List
A value is appended in copy list but the original list remains unchanged. This shows that the lists are independent.
a = [1, 2, 3]
# Copy the list
b = a.copy()
# Add an element to the copied list
b.append(4)
print('a:', a)
print('b:', b)
Output
a: [1, 2, 3] b: [1, 2, 3, 4]
Copying a List of Lists (Shallow Copy)
Even though copy() creates a new list but it is a shallow copy. Modifying the inner list in copied list also affects original list because both lists reference the same inner lists.
a = [[1, 2], [3, 4]]
b = a.copy()
# Modify the value at index 0,0 in the copied list
b[0][0] = 100
print("a:", a)
print("b:", b)
Output
a: [[100, 2], [3, 4]] b: [[100, 2], [3, 4]]
Copying a List with Mixed Data Types
In the below example, ‘b’ is a shallow copy of a list with mixed data types (integers, strings, lists, and dictionaries). After modifying the nested list inside copied list ‘b’ affects original list ‘a’ because it’s a shallow copy.
a = [1, 'two', 3.0, [4, 5], {'key': 'value'}]
b = a.copy()
# Add an element (6) in the copied list at index 3
b[3].append(6)
print("a:", a)
print("b:", b)
Output
a: [1, 'two', 3.0, [4, 5, 6], {'key': 'value'}] b: [1, 'two', 3.0, [4, 5, 6], {'key': 'value'}]
Related Articles:
- Cloning or Copying a list in Python
- Deep and Shallow copy in Python
- How to copy a nested list in Python