Computer Science
t1 = (100, 200, "Global", 3, 3.5, "Exam", [1, 2], (30, 40), (3, 5, 3)) :
Consider the above tuple 't1' and answer the following questions:
(a) len(t1)
(b) 20 not in t1
(c) t1[-8:-4]
(d) t1[5:]
(e) t1.index(5)
(f) t1.index(3, 6)
(g) 10 in t1
(h) t1.count(3)
(i) any(t1)
(j) t1[2]*2
Python Tuples
2 Likes
Answer
(a) len(t1) — 9
(b) 20 not in t1 — True
(c) t1 [-8:-4] — (200, 'Global', 3, 3.5)
(d) t1 [5:] — ('Exam', [1, 2], (30, 40), (3, 5, 3))
(e) t1.index (5) — It raises an error.
(f) t1.index (3, 6) — It raises an error.
(g) 10 in t1 — False
(h) t1.count (3) — 1
(i) any (t1) — True
(j) t1[2]*2 — GlobalGlobal
Explanation
(a) The len() function returns the number of elements in the tuple. Hence, len(t1) returns 9.
(b) The not in operator checks if an element is not present in the tuple. Hence, 20 not in t1 returns True because 20 is not an element of the tuple t1.
(c) It uses negative indexing to select elements from the 8th position from the end to the 4th position from the end.
(d) This slices the tuple starting from the index 5 to the end.
(e) The index() method returns the first index of the specified element. Hence, t1.index(5) raises an Error because 5 is not an element of the tuple.
(f) It raises an error because there is no occurrence of the element 3 after index 6.
(g) The in operator checks if a specified value is present in the tuple. For 10 in t1, it returns False because 10 is not an element of the tuple t1.
(h) The count() method returns the number of occurrences of 3 in the tuple. Hence, t1.count(3) returns 2 because 3 appears twice in the tuple.
(i) The any() function in Python is a built-in function that returns True if at least one element in a given iterable (such as a list, tuple, or set) is True. If all elements are False, it returns False. Hence, any(t1) returns True because the elements in the tuple are True.
(j) The statement t1[2] is accessing the third element of the tuple t1, which is the string "Global". The statement t1[2]*2 is attempting to multiply the accessed element by 2. However, since the element is a string, it will repeat the string "Global" twice, resulting in "GlobalGlobal".
Answered By
2 Likes
Related Questions
Consider the following code and find out the error:
T1 = ('A') T2 = ('B', 'C', 3) T3 = T1 + T2Consider the following code and find out the error:
T1 = (10, 20, 30, 40) T2 = (40, 50, 60) T1, T2, T3 = T1, T2Write the output of the following statements:
(a) >>> tuple([10,20,40])
(b) >>> ("Tea",)*5
(c) >>> tuple ("Item")
Consider two tuples t1 & t2 given below:
t1 = (100, 200, 300) t2 = (10, 20, 30, 40)Write the output of the following statements:
(a)
t1, t2 = t2, t1 print(t1) print (t2)(b)
print (t1!=t2)(c)
print (t1 < t2)