Adding Item in Tuple

Write a Python program to add an item to a tuple. Return the new tuple.

Example 1:

Input: (5, 'hello', 8.3), 6 
Output: (5, 'hello', 8.3, 6)

Example 2:

Input: (7, 'world', 3.14, 'd'), 'new' 
Output: (7, 'world', 3.14, 'd', 'new')

Tuples are immutable, you cannot directly add an item. However, you can concatenate the original tuple with another tuple containing the new item.

def add_item(t, item):
    t += (item,)
    return t

© Let’s Data Science


Unlock AI & Data Science treasures. Log in!