Computer Science
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[:]
Python Tuples
7 Likes
Answer
The values of variables a, b, c, d, e, f, g, h after the statements will be:
a ⇒ ( )
b ⇒ (80, 88, 83, 86)
c ⇒ (88, 85)
d ⇒ (88, 85, 80, 88)
e ⇒ (83, 86)
f ⇒ (80, 88)
g ⇒ ( )
h ⇒ (88, 85, 80, 88, 83, 86)
Explanation
perc[2:2]
specifies an invalid range as start and stop indexes are the same. Hence, an empty slice is stored in a.- Since stop index is not specified,
perc[2:]
will return a tuple slice containing elements from index 2 to the last element. - Since start index is not specified,
perc[:2]
will return a tuple slice containing elements from start to the element at index 1. - Length of Tuple is 6 and
perc[:-2]
implies to return a tuple slice containing elements from start tillperc[ : (6-2)] = perc[ : 4]
i.e., the element at index 3. - Length of Tuple is 6 and
perc[-2: ]
implies to return a tuple slice containing elements fromperc[(6-2): ] = perc[4 : ]
i.e., from the element at index 4 to the last element. - Length of Tuple is 6 and
perc[2:-2]
implies to return a tuple slice containing elements from index 2 toperc[2:(6-2)] = perc[2 : 4]
i.e., to the element at index 3. - Length of Tuple is 6 and
perc[-2: 2]
implies to return a tuple slice containing elements fromperc[(6-2) : 2] = perc[4 : 2]
i.e., index at 4 to index at 2 but that will yield empty tuple as starting index has to be lower than stopping index which is not true here. - It will return all the elements since start and stop index is not specified.
Answered By
3 Likes
Related Questions
Find the output generated by following code fragments :
t3 = (6, 7) t4 = t3 * 3 t5 = t3 * (3) print(t4) print(t5)
Find the output generated by following code fragments :
t1 = (3,4) t2 = ('3' , '4') print(t1 + t2 )
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]
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])