Python | Remove empty tuples from a list


When it is required to remove empty tuples from a list of tuples, a simple loop can be used.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

A list of tuple basically contains tuples enclosed in a list.

Below is a demonstration for the same −

Example

 Live Demo

def remove_empty(my_tuple):
   my_tuple = [t for t in my_tuple if t]
   return my_tuple
my_tuple = [(), (), (''), (" " , " "), (45, 67, 35, 66, 74, 89, 100) , 'jane']
print("The tuple is : ")
print(my_tuple)
print("The method to remove empty tuples is being called...")
my_result = remove_empty(my_tuple)
print("The list of tuple after remvoing empty tuples is : ")
print(my_result)

Output

The tuple is :
[(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
The method to remove empty tuples is being called...
The list of tuple after remvoing empty tuples is :
[(' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']

Explanation

  • A method named ‘remove_empty’ is defined, that takes a list of tuple as parameter.
  • It iterates through the tuple and returns values only if they are non-empty.
  • A list of tuple is defined, and is displayed on the console.
  • The method is called by passing this list of tuple.
  • This operation’s data is assigned to a variable.
  • It is then displayed as output on the console.

Updated on: 11-Mar-2021

713 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements