copy()
方法返回 列表 的浅拷贝。
示例
# 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() 语法
copy()
方法的语法是
new_list = list.copy()
copy() 参数
copy()
方法不接受任何参数。
copy() 返回值
copy()
方法返回一个新列表。它不会修改原始列表。
示例:复制列表
# mixed list
my_list = ['cat', 0, 6.7]
# copying a list
new_list = my_list.copy()
print('Copied List:', new_list)
输出
Copied List: ['cat', 0, 6.7]
如果您修改上述示例中的 new_list,my_list 将不会被修改。
使用 = 复制列表
我们也可以使用 =
运算符 来复制列表。例如,
old_list = [1, 2, 3] new_list = old_list
然而,通过这种方式复制列表存在一个问题。如果您修改 new_list,old_list 也会被修改。这是因为新列表引用或指向同一个 old_list 对象。
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)
输出
Old List: [1, 2, 3, 'a'] New List: [1, 2, 3, 'a']
但是,如果您希望在新列表被修改时原始列表保持不变,可以使用 copy()
方法。
相关教程: Python 浅拷贝与深拷贝
示例:使用切片语法复制列表
# 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)
输出
Old List: ['cat', 0, 6.7] New List: ['cat', 0, 6.7, 'dog']
另请阅读