The copy() method returns a shallow copy of the list.
Example
copy() Syntax
The syntax of the copy() method is:
new_list = list.copy()
copy() Parameters
The copy() method doesn't take any parameters.
copy() Return Value
The copy() method returns a new list. It doesn't modify the original list.
Example: Copying a List
Output
Copied List: ['cat', 0, 6.7]
If you modify the new_list in the above example, my_list will not be modified.
List copy using =
We can also use the = operator to copy a list. For example,
old_list = [1, 2, 3] new_list = old_list
Howerver, there is one problem with copying lists in this way. If you modify new_list, old_list is also modified. It is because the new list is referencing or pointing to the same old_list object.
Output
Old List: [1, 2, 3, 'a'] New List: [1, 2, 3, 'a']
However, if you need the original list unchanged when the new list is modified, you can use the copy() method.
Related tutorial: Python Shallow Copy Vs Deep Copy
Example: Copy List Using Slicing Syntax
Output
Old List: ['cat', 0, 6.7] New List: ['cat', 0, 6.7, 'dog']