English

TypeError occurs while statement 2 is running. Give reason. How can it be corrected? >>> tuple1 = (5) #statement 1 >>> len(tuple1) #statement 2

Advertisements
Advertisements

Question

TypeError occurs while statement 2 is running. Give reason. How can it be corrected?

>>> tuple1 = (5)         #statement 1
 >>> len(tuple1)         #statement 2
Short/Brief Note
Advertisements

Solution

The ‘statement 1’ is creating a variable, tuple1 which is of ‘int’ data type. The ‘statement 2’ is checking for the length of the variable, but the argument passed is an ‘int’ data type. The 'len()' function can return the length only when the object is a sequence or a collection. This is the reason for the type error. 

The error can be corrected by adding one comma after ‘5’ in statement 1, as this will create a tuple and as a tuple is a collection, the 'len()' function will not return an error. The correct statement will be:

>>> tuple1 = (5,)
>>> len(tuple1)
shaalaa.com
Concepts of Tuples in Python
  Is there an error in this question or solution?
Chapter 10: Tuples and Dictionaries - Exercise [Page 224]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 10 Tuples and Dictionaries
Exercise | Q 8. | Page 224
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×