Find out the effect of the following code fragments:
a. plane = (“Passengers”, ”Luggage”)
plane [1] = “Snakes”
b. (a, b, c) = (1,2,3)
c. (a, b, c, d) = (1,2,3)
d. a, b, c, d = (1,2,3)
e. t1=(2,3,4,5,6)
a, b, c, d, e = (p, q, r, s, t) = t1
f. T=(12)
Answers
Answer:
(a) Error – tuples are immutable
(b) a = 1, b = 2, c = 3
(c) Error – not enough items to unpack
(d) Error – too many items to unpack
(e) a = p = 2, b = q = 3, c = r = 4, d = s = 6, r = t = 6
(f) T = 12
Explanation:
(a) Tuples are an immutable data type, i.e., once declared, they cannot be changed. So, there will be an error. If we want to use this code snippet properly, we can use a list [] instead.
(b) We work on the tuple (1, 2, 3) and assign its values index-by-index to the tuple on the LHS. This process is called unpacking.
(c) We try to unpack the tuple but, since more items are provided on LHS, there is an error. Unpacking can only happen correctly if the number of items on both hand sides is equal.
(d) We try to unpack the tuple but, since more items are provided on RHS, there is an error. Look at part (c) for a detailed explanation.
(e) This is just unpacking the tuple t1 but, instead of unpacking it into one set of variables (or one tuple), we are doing so with multiple tuples.
(f) The variable T is assigned the integer value of 12. It may seem that (12) is a tuple but this is no so. Python only considers elements surrounded by parenthesis as tuples if they have more than one element. If we wanted to make T a tuple containing just the number 12, we could do this instead:-
T = (12,)
Notice the comma after 12, this indicates to Python that this is not an integer but, a tuple of length 1.