Python | Remove empty tuples from a list

Python Methods and Functions

In this article, we will see how we can remove an empty tuple from a given list of tuples. We will find different ways in which we can accomplish this task of deleting tuples using different methods and techniques in Python. 
Examples:

 Input: tuples = [(), ('ram',' 15', '8'), (), (' laxman', 'sita'), (' krishna', 'akbar',' 45'), ('', ''), ()] Output: [('ram',' 15', '8'), (' laxman', 'sita'), ('krishna',' akbar', '45'), (' ',' ')] Input: tuples = [(' ',' ',' 8'), (), ('0',' 00' , '000'), (' birbal', '', '45'), (' '), (), (' ',' '), ()] Output: [(' ',' ',' 8 '), (' 0', '00',' 000'), ('birbal',' ',' 45'), ('', '')] 

Method 1: Using the concept

# Python program to remove empty tuples from
# list of tuples function to remove empty tuples
# using comprehension list

def Remove ( tuples): 

tuples = [t for t in tuples if t]

return tuples

 
Driver code

tuples = [(), ( 'ram' , '15' , ' 8' ), (), ( 'laxman' , ' sita' ), 

  ( ' krishna' , 'akbar' , ' 45' ) , (' ', ' '), ()]

print (Remove (tuples))

Output:

 [('ram',' 15', '8'), (' laxman', 'sita'), (' krishna' , 'akbar',' 45'), ('', '')] 

Method 2: Using the filter () method
Using the built-in filter () method in Python, we can filter out empty elements by passing None as a parameter. This method works in both Python 2 and Python 3 and above, but the desired output is only displayed in Python 2 because Python 3 returns a generator. filter () is faster than list comprehension method. Let's see what happens when we run the program in Python 2.

# Python2 program to remove empty tuples
# from the list of tuples to remove functions
# empty tuples using filter

def Remove (tuples):

  tuples = filter ( None , tuples)

return tuples

  
Driver code

tuples = [(), ( 'ram' , ' 15' , '8' ), (), ( 'laxman' , 'sita' ), 

  ( ' krishna' , 'akbar' , '45' ), (' ', ' '), ()]

print Remove (tuples)

Exit:

 [('ram',' 15', '8'), (' laxman', 'sita'), (' krishna', 'akbar',' 45'), ('', '')] 

Now let's see what happens when we We are trying to run a program in Python 3 or higher. When running the program in Python 3, as mentioned, a generator is returned.

# Python program to remove empty tuples from
# list of function tuples to remove empty ones
# tuples using filter

def Remove (tuples):

  tuples = filter ( None , tuples)

return tuples

  
Driver code

tuples = [(), ( 'ram' , ' 15' , '8' ), (), ( 'laxman' , 'sita' ), 

  ( ' krishna' , 'akbar' , '45' ), (' ', ' '), ()]

print (Remove (tuples))

Output:

 & lt; filter object at 0x7fe26eb0f3c8 & gt;