Q. Following code is trying to create a tuple with a single item. But when we try to obtain the length of the tuple is, Python gives error. Why? What is the solution ?
>>> t = (6)
>>> len(t)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
len(t)
TypeError: object of type 'int' has no len()
>>>
Answer :-
The syntax for a tuple with a single item requires the item to be followed by a comma as
shown below:
t = (6,)
Thus, above code is not creating a tuple in t but an integer, on which len() cannot be applied. To create a tuple in t with single element, the code should be modified as:
>>> t = (6,)
>>> len(t)
Post a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )