Computer Science

Predict the output.

x = (1, (2, (3, (4,))))  
print(len(x))  
print( x[1][0] )   
print( 2 in x )  
y = (1, (2, (3,), 4), 5)  
print( len(y) )   
print( len(y[1]))  
print( y[2] + 50 )
z = (2, (1, (2, ), 1), 1)
print( z[z[z[0]]])

Python Tuples

4 Likes

Answer

Output
2
2
False
3
3
55
(1, (2,), 1)  
Explanation
  • print(len(x)) will return 2. x is a nested tuple containing two elements — the number 1 and another nested tuple (2, (3, (4,))).
  • print( x[1] [0] ) Here, x[1] implies first element of tuple which is (2,(3,(4,))) and x[1] [0] implies 0th element of x[1] i.e. 2 .
  • print( 2 in x ) "in" operator will search for element 2 in tuple x and will return ""False"" since 2 is not an element of parent tuple "x". Parent tuple "x" only has two elements with x[0] = 1 and x[1] = (2, (3, (4,))) where x[1] is itself a nested tuple.
  • y = (1, (2, (3,), 4), 5) y is a nested tuple containing three elements — the number 1 , the nested tuple (2, (3,), 4) and the number 5. Therefore, print( len(y) ) will return 3.
  • print( len(y[1])) will return "3". As y[1] implies (2, (3,), 4). It has 3 elements — 2 (number), (3,) (tuple) and 4 (number).
  • print( y[2] + 50 ) prints "55". y[2] implies second element of tuple y which is "5". Addition of 5 and 50 gives 55.
  • print( z[z[z[0]]]) will return (1, (2,), 1).
    z[0] is equivalent to 2 i.e., first element of tuple z.
    Now the expression has become z[z[2]] where z[2] implies third element of tuple i.e. 1.
    Now the expression has become z[1] which implies second element of tuple i.e. (1, (2,), 1).

Answered By

2 Likes


Related Questions