'Why do tuples not get changed whereas lists do?
Why does only the first tuple change 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)
Solution 1:[1]
In List
when you use this '=' assignment operator, it does not creates new reference, it refers same object.
In Tuple
when you use this '=' assignment operator, it creates new reference.
Refer below code, check the output of ID.
L1 = [1,2,3,4]
L2 = L1
L2.append(5)
print("L1: ", L1)
print("L2: ", L2)
print("ID of L1: ", id(L1))
print("ID of L2: ", id(L2))
# Output =
# L1: [1, 2, 3, 4, 5]
# L2: [1, 2, 3, 4, 5]
# ID of L1: 2598160167616
# ID of L2: 2598160167616
# -------------------------------------------
L1=(1,2,3,4)
L2=L1
L2 += (5,)
print("L1: ", L1)
print("L2: ", L2)
print("ID of L1: ", id(L1))
print("ID of L2: ", id(L2))
# Output =
# L1: (1, 2, 3, 4)
# L2: (1, 2, 3, 4, 5)
# ID of L1: 2598161745696
# ID of L2: 2598161718864
# -------------------------------------------
Solution 2:[2]
In example 1, we have a list. List is mutable, which means once the lists are created they can be changed later. Hence the memory location at which they are stored remains the same. "L2=L1" statement is just providing reference of L1 to L2 and when changes are done in L2 they are reflected in L1 as well.
In example 2, we have tuples. Tuples on the other hand are immutable, which means they cannot be changed further. And that is the reason why L1 was not changing along with L2 because both of them are separate objects with separate memory references.
Solution 3:[3]
Tuples are immutable, so only L2 is changing. As lists are mutable, both are changing then.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Hardik Pachory |
Solution 3 | B--rian |