Python 中的 copy() 函数有助于返回给定列表的浅拷贝。这里的浅拷贝意味着在新列表中所做的任何更改都不会反映到原始列表中。
list.copy() #where list in which needs to copy
copy() 函数不接受任何参数。列表也可以通过使用“=”运算符来复制。通过这种方式复制存在的问题是,如果我们修改复制后的新列表,它也会影响原始列表,因为新列表引用的是同一个原始列表对象。
此方法通过复制原始列表返回一个新列表。它不会对原始列表进行任何更改。
| 输入 | 返回值 |
|---|---|
| 如果列表 | 列表的浅拷贝 |
# 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']