Python program to clear tuple elements

In this program, we are given a tuple consisting of integer elements. And Our task is to create a Python program to clear the tuple elements.
Submitted by Shivang Yadav, on November 02, 2021

While working with collections we need to perform tasks like selective deletion and full deletion of tuple elements in order to improve the working of the program. Here, we will create a Python program to delete all the elements of the tuple.

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

clearing tuple elements

In this program, we have a tuple consisting of elements. Our task is to clear tuple elements from the tuple. To perform this task, we have multiple methods in Python.

Method 1:

One method to solve the problem is by converting the tuple to a list using the list() method, clearing it using the clear() method, and then converting it back to a tuple using the tuple() method.

# Python program to clear Tuple elements 
 
# Creating and printing the tuple 
myTuple = (1, 5, 3, 6, 8)
print("Initial elements of the tuple : " + str(myTuple))
 
# Clearing All tuple elements from the Tuple 
convList = list(myTuple)
convList.clear()
emptyTuple = tuple(convList)

# Printing empty tuple  
print("Printing empty Tuple : " + str(emptyTuple))

Output:

Initial elements of the tuple : (1, 5, 3, 6, 8)
Printing empty Tuple : ()

Method 2:

An alternate method to solve the problem is by reinitializing the tuples by an empty tuple which will delete all its elements and give an empty tuple. This is done by reinitializing the tuple using the tuple() method.

# Python program to clear Tuple elements 
# using tuple method 
 
# Creating and printing the tuple 
myTuple = (1, 5, 3, 6, 8)
print("Initial elements of the tuple : " + str(myTuple))
 
# Clearing All tuple elements from the Tuple 
emptyTuple = tuple()

# Printing empty tuple  
print("Printing empty Tuple : " + str(emptyTuple))

Output:

Initial elements of the tuple : (1, 5, 3, 6, 8)
Printing empty Tuple : ()

Python Tuple Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.