w3resource

Python Exercise: Add an item in a tuple

Python tuple: Exercise-5 with Solution

Write a Python program to add an item to a tuple.

Visual Presentation:

Python Tuple: Add an item in a tuple.
Python Tuple: Add an item in a tuple.

Sample Solution:

Python Code:

# Create a tuple containing a sequence of numbers
tuplex = (4, 6, 2, 8, 3, 1)
# Print the contents of the 'tuplex' tuple
print(tuplex)

# Tuples are immutable, so you can't add new elements directly.
# To add an element, create a new tuple by merging the existing tuple with the desired element using the + operator.
tuplex = tuplex + (9,)
# Print the updated 'tuplex' tuple
print(tuplex)

# Adding items at a specific index in the tuple.
# This line inserts elements (15, 20, 25) between the first five elements and duplicates the original five elements.
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
# Print the modified 'tuplex' tuple
print(tuplex)

# Convert the tuple to a list.
listx = list(tuplex)
# Use different methods to add items to the list.
listx.append(30)
# Convert the modified list back to a tuple to obtain 'tuplex' with the added element.
tuplex = tuple(listx)
# Print the final 'tuplex' tuple with the added element
print(tuplex) 

Sample Output:

(4, 6, 2, 8, 3, 1)                                                                                            
(4, 6, 2, 8, 3, 1, 9)                                                                                         
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)                                                                    
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30) 

Flowchart:

Flowchart: Add an item in a tuple

Python Code Editor:

Previous: Write a Python program to unpack a tuple in several variables.
Next: Write a Python program to convert a tuple to a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/tuple/python-tuple-exercise-5.php