KnowledgeBoat Logo

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
  1. perc[2:2] specifies an invalid range as start and stop indexes are the same. Hence, an empty slice is stored in a.
  2. Since stop index is not specified, perc[2:] will return a tuple slice containing elements from index 2 to the last element.
  3. Since start index is not specified, perc[:2] will return a tuple slice containing elements from start to the element at index 1.
  4. Length of Tuple is 6 and perc[:-2] implies to return a tuple slice containing elements from start till perc[ : (6-2)] = perc[ : 4] i.e., the element at index 3.
  5. Length of Tuple is 6 and perc[-2: ] implies to return a tuple slice containing elements from perc[(6-2): ] = perc[4 : ] i.e., from the element at index 4 to the last element.
  6. Length of Tuple is 6 and perc[2:-2] implies to return a tuple slice containing elements from index 2 to perc[2:(6-2)] = perc[2 : 4] i.e., to the element at index 3.
  7. Length of Tuple is 6 and perc[-2: 2] implies to return a tuple slice containing elements from perc[(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.
  8. It will return all the elements since start and stop index is not specified.

Answered By

3 Likes


Related Questions