Write A Python Program To Remove An Empty Tuple(S) From A List Of Tuples

Given a list containing tuples,  the tuples might be storing data (string/ integers/ floating point values) or it may be empty tuple,  your Python logic should identify the tuples which are empty and you it should remove empty tuples from the list and then finally print the list.


let's try to understand this Python program

 

Write A Python Program To Remove An Empty Tuple(S) From A List Of Tuples

 



Write A Python Program To Remove An Empty Tuple(S) From A List Of Tuples

Let's declare the list containing tuples inside the program,  that is if you're looking at the below statement “my_list” Is the variable that is storing the list containing tuples.  The list contains one integer value, 6 tuples out of which two are empty.

my_list = [(1, 2), 23, ("hello", "hi", "hey"), (), (2.3, 8.9), (), (100, 90)]




Once we get our input list now our task is to to remove the empty tuples,  let's take a variable named empty_tuple and assign an empty tuple to it using tuple() function call.

empty_tuple = tuple()




Now enumerate the given input list To get the index as well as the list item at the same time,  enumerate it using the for loop.  using the if statement check if the list item is an Empty tuple,  if so take the index and using the list index delete the list item.  This  is how you delete an empty tuple.

for index, item in enumerate(my_list):
   if item == empty_tuple:
       del my_list[index]




Once you delete all the empty tables using the print statement print the user-friendly message as shown below and then print  the list.  you can notice that the  empty tuples present in the list have been deleted

print("The List After Removing Empty Tuples is ...")
print(my_list)



Code
======================

my_list = [(1, 2), 23, ("hello", "hi", "hey"), (), (2.3, 8.9), (), (100, 90)]
empty_tuple = tuple()
for index, item in enumerate(my_list):
   if item == empty_tuple:
       del my_list[index]

print("The List After Removing Empty Tuples is ...")
print(my_list)





OUTPUT
============

The List After Removing Empty Tuples is ...
[(1, 2), 23, ('hello', 'hi', 'hey'), (2.3, 8.9), (100, 90)]



You can also change the list containing tuples as well as empty tuples and try to to run the program again.



Conclusion
======================
Change the input list and try to execute the above program,  note down the results.

Comment it down below if you want me to solve the same problem for nested tuple, i.e, tuple with in a tuple / empty tuple with in a tuple.

 


Post a Comment

0 Comments