English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The copy() method returns a shallow copy of the list.
listcan be copied using=Operators. For example:
old_list = [1, 2, 3] new_list = old_list
The problem with copying lists in this way is that if you modify new_list, old_list will also be modified.
old_list = [1, 2, 3] new_list = old_list # Add an element to the list new_list.append('a') print('New list:', new_list) print('Old list:', old_list)
When running the program, the output is:
New list: [1, 2, 3, 'a'] Old list: [1, 2, 3, 'a']
However, if you need the original list to remain unchanged while modifying the new list, you can use the copy() method. This is called a shallow copy.
The syntax of the copy() method is:
new_list = list.copy()
copy() has no parameters.
The copy() function returns a list. It does not modify the original list.
# Mixed list list = ['猫', 0, 6.7] # Copy a list new_list = list.copy() # Add an element to the new list new_list.append('狗') # Print the new and old lists print('Old list: ', list) print('New list: ', new_list)
When running the program, the output is:
Old list: ['猫', 0, 6.7] New list: ['猫', 0, 6.7, 'dog']
As you can see, even if the new list is modified, the old list remains unchanged.
You can also achieve the same result using slicing:
# Mixed list list = ['cat', 0, 6.7] # Copy a list using slicing new_list = list[:] # Add an element to the new list new_list.append('dog') # Print the new and old lists print('Old list: ', list) print('New list: ', new_list)
After running, the output result is:
Old list: ['cat', 0, 6.7] New list: ['cat', 0, 6.7, 'dog']