# id()函數能夠獲取變量在內存中的地址標識 num1 = 2; num2 = 2; print(id(num1)) # result:8791124202560 print(id(num2)) # result:8791124202560 str1 = '123' str2 = '123' print(id(str1)) # result:39986040 print(id(str2)) # result:39986040
結論:對於數字和字符串來講,賦值時若是有相同的值在python管理的內存中,python內部會把這個值的引用(地址)指向被賦值的變量python
1 from copy import * 2 list1 = [1, {'a': 1, 'b': 2}, ('a', 'b', 'c')] 3 list2 = list1 4 #列表 5 print(id(list1)) # result:30433928 6 print(id(list2)) # result:30433928 7 #字典 8 print(id(list1[1])) # result:31017792 9 print(id(list2[1])) # result:31017792 10 #元組 11 print(id(list1[2])) # result:35446576 12 print(id(list1[2])) # result:35446576
結論:對於賦值,列表,字典,元組用的都是同一塊地址函數
1 from copy import * 2 str1 = '123' 3 str2 = copy(str1) # 使用copy模塊裏的copy()函數進行淺拷貝 4 print(id(str1)) # result:31204496 5 print(id(str2)) # result:31204496 6 num1 = 3 7 num2 = copy(num1) 8 print(id(num1)) # rsult:8791078065248 9 print(id(num2)) # rsult:8791078065248
結論:數字和字符串的淺拷貝,與賦值相同,在內存當中用的也是同一個地址
spa
1 from copy import * 2 list1 = [1, {'a': 1, 'b': 2}, ('a', 'b', 'c')] 3 list2 = copy(list1) 4 # 列表 5 print(id(list1)) # result:42354568 6 print(id(list2)) # result:42227400 7 # 字典 8 print(id(list1[1])) # result:30952256 9 print(id(list2[1])) # result:30952256 10 # 元組 11 print(id(list1[2])) # result:41082600 12 print(id(list2[2])) # result:41082600 13 14 tuple1 = (1, {'a': 1, 'b': 2}, ['a', 'b', 'c']) 15 tuple2 = copy(tuple1) 16 # 元組 17 print(id(tuple1)) # result:35668112 18 print(id(tuple2)) # result:35668112 19 # 字典 20 print(id(tuple1[1])) # result:30821256 21 print(id(tuple2[1])) # result:30821256 22 # 列表 23 print(id(tuple1[2])) # result:35862792 24 print(id(tuple2[2])) # result:35862792
結論:對於列表和字典,淺拷貝會拷貝第一層引用(但最外層是元組時,不會拷貝).code
1 from copy import * 2 str1 = '123' 3 str2 = deepcopy(str1) # 使用copy模塊裏的copy()函數進行淺拷貝 4 print(id(str1)) # result:31269752 5 print(id(str2)) # result:31269752 6 num1 = 3 7 num2 = deepcopy(num1) 8 print(id(num1)) # rsult:8791074002016 9 print(id(num2)) # rsult:8791074002016
結論:不管是賦值或是淺拷貝亦或是深拷貝,字符串和數字都是用同一個地址blog
1 from copy import * 2 list1 = [1, {'a': 1, 'b': 2}, [1, 2, 3], ('a', 'b', 'c')] 3 list2 = deepcopy(list1) 4 # 外層列表 5 print(id(list1)) # result:32134984 6 print(id(list2)) # result:32133768 7 # 字典 8 print(id(list1[1])) # result:4410176 9 print(id(list2[1])) # result:31862720 10 # 列表 11 print(id(list1[2])) # result:32262088 12 print(id(list2[2])) # result:32262408 13 # 元組 14 print(id(list1[3])) # result:32038704 15 print(id(list2[3])) # result:32038704
結論:深拷貝會對列表和字典進行拷貝,但對於元組,深淺拷貝都會失效.內存