Home » Python

Clearing a tuple in Python

Python | Clearing tuple: Here, we are going to learn about the various methods to clear a tuple in Python programming language?
Submitted by IncludeHelp, on April 08, 2020

Python | Clearing tuple

While working with the tuples, we may need to clear its elements/records. In this tutorial, we are discussing some of the methods to clear a tuple.

Method 1: Reinitialize the tuple using pair of round brackets ()

A non-empty tuple can be reinitialized using a pair of round brackets () to clear the tuple.

# Clearing a tuple in Python | Method 1

# tuple creation
x = ("Shivang", 21, "Indore", 9999867123)

# printing original tuple
print("x: ", x)
print("len(x): ", len(x))
print("type(x): ", type(x))
print()

# clearing tuple by reinitialize it using 
# pair of round brackets "()"
x = ()
print("After clearing tuple....")
print("x: ", x)
print("len(x): ", len(x))
print("type(x): ", type(x))
print()

Output

x:  ('Shivang', 21, 'Indore', 9999867123)
len(x):  4
type(x):  <class 'tuple'>

After clearing tuple....
x:  ()
len(x):  0
type(x):  <class 'tuple'>

Method 2: Reinitialize the tuple using tuple()

A non-empty tuple can be reinitialized using tuple() to clear the tuple.

# Clearing a tuple in Python | Method 2

# tuple creation
x = ("Shivang", 21, "Indore", 9999867123)

# printing original tuple
print("x: ", x)
print("len(x): ", len(x))
print("type(x): ", type(x))
print()

# clearing tuple by reinitialize it using "tuple()"
x = tuple()
print("After clearing tuple....")
print("x: ", x)
print("len(x): ", len(x))
print("type(x): ", type(x))
print()

Output

x:  ('Shivang', 21, 'Indore', 9999867123)
len(x):  4
type(x):  <class 'tuple'>

After clearing tuple....
x:  ()
len(x):  0
type(x):  <class 'tuple'>

Method 3: Converting Tuple to List, clearing list and then converting it to Tuple again

Since tuple doesn't have any library function to clear its elements. We can 1) convert a tuple to the list using the list() method, 2) clear the list using List.clear() method, and 3) convert empty list to the tuple again using the tuple() function. This method can also be used to clear the tuple.

# Clearing a tuple in Python | Method 3

# tuple creation
x = ("Shivang", 21, "Indore", 9999867123)

# printing original tuple
print("x: ", x)
print("len(x): ", len(x))
print("type(x): ", type(x))
print()

# clearing tuple by converting Tuple to List, 
# clearing list and then converting it 
# to Tuple again
temp_list = list(x)   # converting to list
temp_list.clear()     # clearing list
x = tuple(temp_list)  # converting to tuple

print("After clearing tuple....")
print("x: ", x)
print("len(x): ", len(x))
print("type(x): ", type(x))

Output

x:  ('Shivang', 21, 'Indore', 9999867123)
len(x):  4
type(x):  <class 'tuple'>

After clearing tuple....
x:  ()
len(x):  0
type(x):  <class 'tuple'>


Comments and Discussions!

Load comments ↻





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