python 中的copy()
函數有助于返回給定列表的淺層副本。在這里,淺拷貝意味著在新列表中所做的任何更改都不會反映原始列表。
**list.copy()** #where list in which needs to copy
復制()參數:
copy()
函數不接受任何參數。也可以使用“ = ”運算符復制列表。通過以這種方式復制,問題是,如果我們修改復制的新列表,它將影響原始列表,因為新列表引用相同的原始列表對象。
復制()返回值
此方法通過復制原始列表返回一個新列表。它不會對原始列表進行任何更改。
| 投入 | 返回值 | | 如果列表 | 列表的簡單副本 |
Python 中copy()
方法的示例
示例 1:如何復制列表?
# 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]
示例 2:如何使用切片語法復制列表?
# 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']