Q:

Python program to clear tuple elements

belongs to collection: Python Tuple Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 : ()

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Sum of tuple elements... >>
<< Python | Flatten Nested Tuples...