Computer Science
What does each of the following expressions evaluate to? Suppose that T is the tuple containing :("These", ["are" , "a", "few", "words"] , "that", "we", "will" , "use")
T[1][0: :2]
"a" in T[1][0]
T[:1] + [1]
T[2::2]
T[2][2] in T[1]
Python Tuples
7 Likes
Answer
The given expressions evaluate to the following:
['are', 'few']
True
TypeError: can only concatenate tuple (not "list") to tuple
('that', 'will')
True
Explanation
- T[1] represents first element of tuple i.e., the list ["are" , "a", "few", "words"]. [0 : : 2] creates a list slice starting from element at index zero of the list to the last element including every 2nd element (i.e., skipping one element in between).
- "in" operator is used to check elements presence in a sequence. T[1] represents the list ["are" , "a", "few", "words"]. T[1][0] represents the string "are". Since "a" is present in "are", it returns true.
- T[:1] is a tuple where as [1] is a list. They both can not be concatenated with each other.
- T[2::2] creates a tuple slice starting from element at index two of the tuple to the last element including every 2nd element (i.e., skipping one element in between).
- T[2] represents the string "that". T[2][2] represents third letter of "that" i.e., "a". T[1] represents the list ["are" , "a", "few", "words"]. Since "a" is present in the list, the in operator returns True.
Answered By
3 Likes
Related Questions
Find the output generated by following code fragments :
t1 = (3,4) t2 = ('3' , '4') print(t1 + t2 )
What will be stored in variables a, b, c, d, e, f, g, h, after following statements ?
perc = (88,85,80,88,83,86) a = perc[2:2] b = perc[2:] c = perc[:2] d = perc[:-2] e = perc[-2:] f = perc[2:-2] g = perc[-2:2] h = perc[:]
Carefully read the given code fragments and figure out the errors that the code may produce.
t = ('a', 'b', 'c', 'd', 'e') print(t[5])
Carefully read the given code fragments and figure out the errors that the code may produce.
t = ('a', 'b', 'c', 'd', 'e') t[0] = 'A'