KnowledgeBoat Logo

Computer Science

When would sum( ) not work for tuples ?

Python Tuples

1 Like

Answer

Sum would not work for the following cases:

  • When tuple does not have numeric value.
    For example:-
    tup = ("a", "b")
    tup_sum = sum(tup)
    TypeError: unsupported operand type(s) for +: 'int' and 'str'

here, "a" and "b" are string not integers therefore they can not be added together.

  • Nested tuples having tuple as element.
    For example:-
a = (1,2,(3,4))  
print(sum(a))  

Output:
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

Here, tuple 'a' is a nested tuple and since it consist of another tuple i.e. (3,4) it's elements can not be added to another tuple. Hence it will throw an error.

  • Tuple containing elements of different data type.
    For example:-
a = (1,2.5,(3,4),"hello")  
print(sum(a))  

Output:
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'

Tuple a contains elements of integer, float, string and tuple type which can not be added together.

Answered By

1 Like


Related Questions