23-python基础-python3-浅拷贝与深拷贝(1)

1.可变和不可变数据类型。

  • 列表是‘可变的’数据类型,它的值可以添加、删除或改变。
  • 字符串是‘不可变的’,它不能被更改。

(1)字符串

  • 尝试对字符串中的一个字符重新赋值,将导致TypeError错误。
1 a = 'abcd'
2 a[0]='e'

3 Traceback (most recent call last): 4 File "C:UserssummerAnaconda3libsite-packagesIPythoncoreinteractiveshell.py", line 2961, in run_code 5 exec(code_obj, self.user_global_ns, self.user_ns) 6 File "<ipython-input-37-93bf15c8bf3d>", line 1, in <module> 7 a[0]='e' 8 TypeError: 'str' object does not support item assignment
  • ‘改变’一个字符串的正确方式,使用切片和连接
1 a = 'abcd'
2 a = a[:1]+'e'+a[1:]
3 a
4  'aebcd'

(2)列表

  • 区别:列表的覆盖和修改
  • 列表覆盖(并不能修改列表,而是创建一个新的列表
1 b = [1,2,3]
2 id(b)
3 Out[42]: 95411912
4 b = [2,3,4]
5 id(b)
6 Out[44]: 95411720
  • 列表修改(在当前列表修改,不会创建新的列表
 1 b = [1,2,3]
 2 id(b)
 3 Out[46]: 93984712
 4 b.append(4)
 5 b
 6 Out[48]: [1, 2, 3, 4]
 7 id(b)
 8 Out[49]: 93984712
 9 del b[0]
10 b
11 Out[51]: [2, 3, 4]
12 id(b)
13 Out[52]: 93984712

(3)元组

  • 元组与列表的主要区别在于,元组像字符串一样,是不可变的。元组不能让它们的值被修改、添加或删除。
1 a = ('hello',1,'a')
2 a[0]=1
3 Traceback (most recent call last):
4   File "C:UserssummerAnaconda3libsite-packagesIPythoncoreinteractiveshell.py", line 2961, in run_code
5     exec(code_obj, self.user_global_ns, self.user_ns)
6   File "<ipython-input-54-f9da761c742a>", line 1, in <module>
7     a[0]=1
8 TypeError: 'tuple' object does not support item assignment

2. 引用

  • 引用是一个值,指向某些数据。
  • 在变量必须保存可变数据类型的值时,例如列表或字典,Python 就使用引用。
  • 将列表赋给一个变量时,实际上是将列表的“引用”赋给了该变量。列表引用是指向一个列表的值。
  • 对于不可变的数据类型的值,例如字符串、整型或元组,Python变量就保存值本身。
 1 spam = [0, 1, 2, 3, 4, 5]
 2 id(spam)
 3 Out[66]: 95545224
 4 cheese = spam
 5 cheese
 6 Out[68]: [0, 1, 2, 3, 4, 5]
 7 id(cheese)
 8 Out[69]: 95545224
 9 cheese[1]='hello'
10 cheese
11 Out[71]: [0, 'hello', 2, 3, 4, 5]
12 spam
13 Out[72]: [0, 'hello', 2, 3, 4, 5]
14 id(cheese)
15 Out[73]: 95545224
16 id(spam)
17 Out[74]: 95545224
原文地址:https://www.cnblogs.com/summer1019/p/11288674.html