简体   繁体   中英

LIST and TUPLE assignment operation

Why only tuple changes in example II whereas both lists get changed in example I? Please consider these two programs and their respective output (I and II).

I .

L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)

Output : L1: [1,2,3,4,5] L2: [1,2,3,4,5]

II .

L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)

Output : L1: (1,2,3,4) L2: (1,2,3,4,5)

a = b makes a refer to the same object as b . But tuples are immutable, so += creates a new tuple, leaving the original untouched.

In the first example, both L1 and L2 are pointing to the stored data so if you change any of L1 or L2, the data changes and by recalling (not sure the right expression) any of L1 or L2, the new changed data will be shown. This explanation was true for lists. Lists are mutable. In the second example, you're using tuples which are immutable . When you want to change an immutable tuple, python automatically makes a new tuple. It means that when you add 5 to the tuple L2, in fact 5 doesn't add up to the original tuple, python makes a new tuple named L2 with the new data (5) added to it and the original data (L1) remains unchanged. This is why L1 is not changed but L2 is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM