The copy() method returns a shallow copy of the list.
Example
# mixed list prime_numbers = [2, 3, 5] # copying a list numbers = prime_numbers.copy() print('Copied List:', numbers) # Output: Copied List: [2, 3, 5] 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
# mixed list my_list = ['cat', 0, 6.7] # copying a list new_list = my_list.copy() print('Copied List:', new_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.
old_list = [1, 2, 3] # copy list using = new_list = old_list # add an element to list new_list.append('a') print('New List:', new_list) print('Old List:', old_list) 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
# shallow copy using the slicing syntax # mixed list list = ['cat', 0, 6.7] # copying a list using slicing new_list = list[:] # Adding an element to the new list new_list.append('dog') # Printing new and old list print('Old List:', list) print('New List:', new_list) Output
Old List: ['cat', 0, 6.7] New List: ['cat', 0, 6.7, 'dog']
Also Read: