Tuples (tuple) It can't be modified , This is also the biggest difference between it and the list .
Since tuples cannot be modified , So why do we mention modifying tuples here ? In fact, we are talking about pseudo modification , That's all “ After modification ” Created a new metagroup , The address of the original tuple is different from that of the new tuple .
“ modify ” Method 1 : Using modifiable objects as mediators
utilize list function ( or set function 、numpy.array function ...) Convert to list ( Or set 、 Array and other modifiable objects ) We'll change it later .
“ modify ” Method 2 : Reassign a new tuple .
e = (1, 2)
f = (3, 4)
print(id(e)) # 2518329767872
print(id(f)) # 2517956197824
Be careful , Even if the assignment is the same , The addresses of two tuples are also different .( list 、 The same is true of containers such as dictionaries )
e = (1, 2)
f = (1, 2)
print(id(e)) # 2518329741824
print(id(f)) # 2518329767872
But for string variables 、 Numerical variable , Assign the same string 、 The number , The two variables are actually the same .
g = 'bguryeidbauisfbsigvb'
h = 'bguryeidbauisfbsigvb'
print(id(g)) # 2518329751952
print(id(h)) # 2518329751952
Modify method 3 : utilize 【+】 To add tuple elements
As you can see from the code , Tuples added h Tuples of elements in j And tuples g Is not the same , Because the address is different .
g = (1,2)
h = (1,2,3)
j = g + h
print(g) # (1,2)
print(h) # (1,2,3)
print(j) # (1,2,1,2,3)
print(id(g)) # 2518329751952
print(id(h)) # 2518329767232
print(id(j)) # 2517955499968
Be careful : Add elements to a tuple , Can't use append; But the list 、 Dictionaries 、 Array 、 It is possible to change containers such as collections !
g = (1,2)
g.append(3) # AttributeError: 'tuple' object has no attribute 'append'
h = [1,2,3]
h.append(4)
print(h) # [1,2,3,4]