The copy() function in python helps to return a shallow copy of the given list. Here the shallow copy means any changes made in the new list won’t reflect the original list.
list.copy() #where list in which needs to copy
The copy() function doesn't take any parameter. The list can be copied by using the '=' operator also. By copying in this way the issue is that, if we modify the copied new list it will affect the original list also because the new list referring to the same original list object.
This method returns a new list by copying the original list. It doesn't make any changes to the original list.
|if list||shallow copy of list|
# mixed list org_list = ['abc', 0, 5.5] # copying a list new_list = org_list.copy() print('Copied List:', new_list)
Copied List: ['abc', 0, 5.5]
# shallow copy using the slicing syntax # mixed list org_list = ['abc', 0, 5.5] # copying a list using slicing new_list = org_list[:] # Adding an element to the new list new_list.append('def') # Printing new and old list print('Original List:', org_list) print('New List:', new_list)
Original List: ['abc', 0, 5.5] New List: ['abc', 0, 5.5,'def']