Computer Science
What will be the output of the following code snippet?
Tup1 = ((1, 2),) * 7
print(len(Tup1[3:8]))
Answer
Output
4
Explanation
*
operator repeats ((1, 2),)
seven times and the resulting tuple is stored in Tup1. Therefore, Tup1 will contain ((1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2))
.
Tup1[3:8]
will create a tuple slice of elements from index 3 to index 7 (excluding element at index 8) but Tup1 has total 7 elements, so it will return tuple slice of elements from index 3 to last element i.e ((1, 2), (1, 2), (1, 2), (1, 2)).len(Tup1[3:8])
len function is used to return the total number of elements of tuple i.e., 4.
Related Questions
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]]])
What will the following code produce ?
Tup1 = (1,) * 3 Tup1[0] = 2 print(Tup1)
Write a Python program that creates a tuple storing first 9 terms of Fibonacci series.
Write a program that receives the index and returns the corresponding value.