Computer Science
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))
Python Tuples
2 Likes
Answer
Output
12
Explanation
This is because tup1 is not a tuple but a string. To make tup1 a tuple it should be initialized as following:tup1 = ('Mega',) * 3
i.e., a comma should be added after the element.
We are getting 12 as output because the string "Mega" has four characters which when replicated by three times becomes of length 12.
Answered By
1 Like
Related Questions
What would be the output of following code if
ntpl = ("Hello", "Nita", "How's", "life?") (a, b, c, d) = ntpl print ("a is:", a) print ("b is:", b) print ("c is:", c) print ("d is:", d) ntpl = (a, b, c, d) print(ntpl[0][0]+ntpl[1][1], ntpl[1])
Predict the output.
tuple_a = 'a', 'b' tuple_b = ('a', 'b') print (tuple_a == tuple_b)
Predict the output.
tuple1 = ('Python') * 3 print(type(tuple1))
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]]])