![]() |
VOOZH | about |
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. Example:
a: [1, 2, 3] b: [1, 2, 3]
Explanation:a.copy() creates a shallow copy of the list a.
list.copy()
Parameters:
Return Type: Returns a shallow copy of a 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] b: [1, 2, 3, 4]
Explanation: After appending 4 to b, the original list a remains unchanged. This shows that a and b are independent lists.
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: [[100, 2], [3, 4]] b: [[100, 2], [3, 4]]
Explanation: Although a and b are separate lists, the nested lists inside them are still shared. Modifying a nested item in b also affects a. This is what makes it a shallow copy.
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, 6], {'key': 'value'}]
b: [1, 'two', 3.0, [4, 5, 6], {'key': 'value'}]
Explanation: Even though a and b are different lists, they both reference the same inner list [4, 5]. So when 6 is appended to b[3], it also changes a[3].
Related Articles: