如何用 python 创建一个列表的副本
时间: 2024-09-12 11:15:47 浏览: 113
在Python中,创建一个列表的副本可以通过几种方式来实现,主要方法包括:
- 使用切片操作符
[:]
:这是创建列表副本的一种简洁方法。通过切片操作,可以得到一个新的列表,其中包含与原列表相同的元素,但它们是独立的,互不影响。
示例代码:
original_list = [1, 2, 3, 4, 5]
copy_list = original_list[:]
- 使用
list()
构造函数:通过list()
函数,可以将其他可迭代对象转换成列表。如果直接对一个列表使用list()
,同样可以得到一个该列表的副本。
示例代码:
original_list = [1, 2, 3, 4, 5]
copy_list = list(original_list)
- 使用
copy
模块中的copy()
函数:copy
模块提供了一个通用的copy()
函数来创建副本,这适用于所有可变类型,包括列表。
示例代码:
import copy
original_list = [1, 2, 3, 4, 5]
copy_list = copy.copy(original_list)
以上三种方法都可以创建一个列表的浅拷贝(shallow copy)。浅拷贝复制了对象的引用,而不是对象本身。如果列表中还包含了其他可变类型的元素(例如其他列表),那么这些内部元素仍然是共享的,对副本中的内部元素的修改会影响原列表。
对于更复杂的情况,比如列表中还包含了其他可变对象,并且需要完全独立的副本(深拷贝,deep copy),可以使用 copy
模块中的 deepcopy()
函数。
示例代码:
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
deep_copy_list = copy.deepcopy(original_list)
相关推荐
















