Python3 list 浅拷贝,深拷贝

简介: Python3 list 浅拷贝,深拷贝

list 浅拷贝,直接赋值形式,修改其中一个list值,两个 list 数据都会变化

list1 = [1, 2, 3, 4]
list2 = list1
print('list1 ', list1)  # list1  [1, 2, 3, 4]
print('list2 ', list2)  # list2  [1, 2, 3, 4]
del list2[0]
print('list1 ', list1)  # list1  [2, 3, 4]
print('list2 ', list2)  # list2  [2, 3, 4]

使用 copy.deepcopy() 实现深拷贝,修改一个 list 数据,其他 list 数据不变

import copy
list3 = [5, 6, 7, 8]
list4 = copy.deepcopy(list3)
print('list3 ', list3)  # list3  [5, 6, 7, 8]
print('list4 ', list4)  # list4  [5, 6, 7, 8]
del list4[0]
print('list3 ', list3)  # list3  [5, 6, 7, 8]
print('list4 ', list4)  # list4  [6, 7, 8]
相关文章
|
25天前
|
运维 Python
【Python】python深拷贝与浅拷贝详解(必须掌握)
【Python】python深拷贝与浅拷贝详解(必须掌握)
|
11天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
20天前
|
索引 Python
Python标准数据类型-List(列表)
Python标准数据类型-List(列表)
42 1
|
1月前
|
Python
请简述Python中的深拷贝和浅拷贝的区别?并举例说明。
【2月更文挑战第25天】【2月更文挑战第84篇】请简述Python中的深拷贝和浅拷贝的区别?并举例说明。
|
1月前
|
存储 安全 Java
Python教程第3章 | 集合(List列表、Tuple元组、Dict字典、Set)
Python 列表、无序列表、字典、元组增删改查基本用法和注意事项
51 1
|
1月前
|
安全 Python
Python中的深拷贝和浅拷贝的区别
Python中的深拷贝和浅拷贝的区别
15 0
|
1月前
|
存储 数据可视化 索引
Python中List列表的妙用
Python中List列表的妙用
18 0
|
1月前
|
存储 索引 Python
Python中的基础数据结构:列表(List)详解
本文将深入探讨Python中的基础数据结构——列表(List),包括其创建、访问、修改、常用操作以及背后的原理。通过示例代码,帮助读者更好地理解和应用列表。
23 0
|
1月前
|
存储 Python
Python中的列表(list)和元组(tuple)区别
Python中的列表(list)和元组(tuple)区别
28 0