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
7 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 withx[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". Asy[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 becomez[z[2]]wherez[2]implies third element of tuple i.e. 1.
Now the expression has becomez[1]which implies second element of tuple i.e.(1, (2,), 1).
Answered By
2 Likes
Related Questions
Find the error. Following code intends to create a tuple with three identical strings. But even after successfully executing following code (No error reported by Python), The len( ) returns a value different from 3. Why ?
tup1 = ('Mega') * 3 print(len(tup1))Predict the output.
tuple1 = ('Python') * 3 print(type(tuple1))What will the following code produce ?
Tup1 = (1,) * 3 Tup1[0] = 2 print(Tup1)What will be the output of the following code snippet?
Tup1 = ((1, 2),) * 7 print(len(Tup1[3:8]))