Open In App

Python | Remove empty tuples from a list

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how can we remove an empty tuple from a given list of tuples. We will find various ways, in which we can perform this task of removing tuples using various methods and ways 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 of List Comprehension 

Python3




# Python program to remove empty tuples from a
# list of tuples function to remove empty tuples
# using list comprehension
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'), ('', '')]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 2: Using the filter() method 

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

Python




# Python2 program to remove empty tuples
# from a list of tuples function to remove
# 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)


Output

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

Now let’s see what happens when we try running the program in Python 3 and above. On running the program in Python 3, as mentioned a generator is returned. 

Python3




# Python program to remove empty tuples from
# a list of tuples function to remove 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))


Output

<filter object at 0x7fae9a596e90>

Method #3 : Using len() method

Python3




# Python program to remove empty tuples from a
# list of tuples function to remove empty tuples
# using len()
 
 
def Remove(tuples):
    for i in tuples:
        if(len(i) == 0):
            tuples.remove(i)
    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'), ('', '')]

Time Complexity: O(n), where n is length of list
Auxiliary Space: O(1)

Method #4 : Using == operator.Check whether the tuple is equal to empty tuple() and remove if equals.

Python3




# Python program to remove empty tuples from a
# list of tuples function to remove empty tuples
def Remove(tuples):
    for i in tuples:
        if(i==()):
            tuples.remove(i)
    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: Using enumerate function

Python3




tuples = [(), ('ram', '15', '8'), (), ('laxman', 'sita'),
          ('krishna', 'akbar', '45'), ('', ''), ()]
res = [t for i, t in enumerate(tuples) if t]
print(res)


Output

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

Time Complexity: O(n)
Auxiliary Space: O(1)

Method: Using while and in operator

Python




# Python program to remove empty tuples from
# a list of tuples function to remove empty
# tuples using while loop and in operator  
def Remove(tuples):
    while () in tuples:
        tuples.remove(());
    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 : Using str(), len() and find() method

Python3




# Python program to remove empty tuples from a
# list of tuples function to remove empty tuples
 
 
def Remove(tuples):
    for i in tuples:
        if(str(i).find("()") != -1 and len(str(i)) == 2):
            tuples.remove(i)
    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: Using lambda functions

Python3




# Python program to remove empty tuples from
# a list of tuples function to remove empty
# tuples using lambda function
 
 
# Driver Code
tuples = [(), ('ram', '15', '8'), (), ('laxman', 'sita'),
          ('krishna', 'akbar', '45'), ('', ''), ()]
 
tuples = list(filter(lambda x: len(x) > 0, tuples))
print(tuples)


Output

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

Method : Using  list comprehension , len() method:

Python3




def remove_empty_tuples(tuples):
    return [t for t in tuples if len(t) > 0]
 
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
          ('krishna', 'akbar', '45'), ('',''),()]
print(remove_empty_tuples(tuples))
#This code is contributed by Edula Vinay Kumar Reddy


Output

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

This method uses a list comprehension to iterate over the list of tuples and check the length of each tuple. If the length is greater than 0, it is included in the new list.

Time complexity: O(n)
Auxiliary Space: O(n)

Method: Using Recursion method 

Python3




#defining recursive function to remove empty tuples in a list
def remove_empty_tuples(start,oldlist,newlist):
  if start==len(oldlist):  #base condition
    return newlist
  if oldlist[start]==():  #checking the element is empty tuple or not
    pass
  else:
    newlist.append(oldlist[start])   #appending non empty tuple element to newlist
  return remove_empty_tuples(start+1,oldlist,newlist)  #recursive function call
 
 
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
          ('krishna', 'akbar', '45'), ('',''),()]
#print('The original list: ',tuples)
print(remove_empty_tuples(0,tuples,[]))
#This code is contributed by tvsk


Output

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

Time complexity: O(n)
Auxiliary Space: O(n)

Method 5: Using itertools.filterfalse()

The itertools module can filter out the elements from a list of tuples. The filterfalse() method in the this module provides us a way to filter out the elements from the list that are false. We can pass an empty tuple as a parameter to the method which will filter out all the empty tuples from the list.

Algorithm:

Import the itertools module
Define the Remove() function and pass tuples as a parameter.
Use the itertools.filterfalse() method to filter out all the empty tuples from the list.
Return the filtered tuples list.
 

Python3




import itertools  # import the itertools module
 
def Remove(tuples):
    tuples = list(itertools.filterfalse(lambda x: x == (), tuples))  # remove empty tuples using filterfalse from itertools
    return tuples
 
# Driver code
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
          ('krishna', 'akbar', '45'), ('',''),()]  # define the input list of tuples
print(Remove(tuples))  # call the Remove function and print the output


Output

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

Time Complexity: O(n) n is length of list of tuples
Auxiliary Space: O(1)

Method 6: Using reduce():
Algorithm:

  1. Define a lambda function remove_empty to append the tuple to the list only if it is not empty, otherwise return the list as it is.
  2. Initialize the list of tuples.
  3. Apply reduce method to the tuples list and the lambda function remove_empty.
  4. The reduce method will return the list with empty tuples removed.
  5. Print the original list and the list after removing empty tuples.

Python3




from functools import reduce
 
# defining lambda function to remove empty tuples
remove_empty = lambda lst, val: lst + [val] if val != () else lst
 
tuples = [(), ('ram','15','8'), (), ('laxman', 'sita'),
          ('krishna', 'akbar', '45'), ('',''),()]
 
# using reduce to remove empty tuples
result = reduce(remove_empty, tuples, [])
 
# printing final result
print("The original list is : " + str(tuples))
print("The list after removing empty tuples : " + str(result))
#This code is contributed by Rayudu.


Output

The original list is : [(), ('ram', '15', '8'), (), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', ''), ()]
The list after removing empty tuples : [('ram', '15', '8'), ('laxman', 'sita'), ('krishna', 'akbar', '45'), ('', '')]

Time Complexity:
The time complexity of the code depends on the number of tuples in the input list. The lambda function remove_empty has a constant time complexity of O(1) for checking if the tuple is empty or not, and the reduce method has a time complexity of O(n) where n is the number of tuples in the input list. Therefore, the overall time complexity of the code is O(n).

Space Complexity:
The space complexity of the code depends on the number of tuples in the input list and the number of non-empty tuples in the input list. The lambda function remove_empty will not create any new objects, and hence the space complexity will be O(1). The reduce method will create a new list object to store the non-empty tuples, and hence the space complexity will be O(m), where m is the number of non-empty tuples in the input list. Therefore, the overall space complexity of the code is O(m).



Previous Article
Next Article

Similar Reads

Python | Remove duplicate tuples from list of tuples
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list. Examples: Input : [(1, 2), (5, 7), (3, 6), (1, 2)] Output : [(1, 2), (5, 7), (3, 6)] Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')] Output : [('a', 'z'), ('a', 'x'), ('z', 'x')] Method #1 : List comprehension This is a naive
5 min read
Python | Remove tuples from list of tuples if greater than n
Given a list of a tuple, the task is to remove all the tuples from list, if it's greater than n (say 100). Let's discuss a few methods for the same. Method #1: Using lambda STEPS: Initialize a list of tuples: ini_tuple = [('b', 100), ('c', 200), ('c', 45), ('d', 876), ('e', 75)]Print the initial list: print("intial_list", str(ini_tuple))Define the
6 min read
Python | Remove tuples having duplicate first value from given list of tuples
Given a list of tuples, the task is to remove all tuples having duplicate first values from the given list of tuples. Examples: Input: [(12.121, 'Tuple1'), (12.121, 'Tuple2'), (12.121, 'Tuple3'), (923232.2323, 'Tuple4')] Output: [(12.121, 'Tuple1'), (923232.2323, 'Tuple4')]Input: [('Tuple1', 121), ('Tuple2', 125), ('Tuple1', 135), ('Tuple4', 478)]
7 min read
Python | Find the tuples containing the given element from a list of tuples
Given a list of tuples, the task is to find all those tuples containing the given element, say n. Examples: Input: n = 11, list = [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [(11, 22), (11, 44)] Input: n = 3, list = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)] Output: [(14, 3), (1, 3), (3, 3)] There are multiple ways we can find the tuples contai
6 min read
Python | Count tuples occurrence in list of tuples
Many a time while developing web and desktop products in Python, we use nested lists and have several queries about how to find the count of unique tuples. Let us see how to get the count of unique tuples in the given list of tuples. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to count unique #
5 min read
Python | Combining tuples in list of tuples
Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways in which this can be performed. Method #1: Using
7 min read
Python | Convert string tuples to list tuples
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to a list of tuples. This kind of problem can have its occurrence in the data science domain. Let's discuss certain ways in which this task can be performed. Method 1 (Using eval() + list
4 min read
Python - Filter all uppercase characters Tuples from given list of tuples
Given a Tuple list, filter tuples that contain all uppercase characters. Input : test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [('GFG', 'IS', 'BEST')] Explanation : Only 1 tuple has all uppercase Strings. Input : test_list = [("GFG", "iS", "BEST"), ("GFg", "AVERAGE"), ("GfG", ), ("Gfg", "CS")] Output : [
8 min read
Python program to find Tuples with positive elements in List of tuples
Given a list of tuples. The task is to get all the tuples that have all positive elements. Examples: Input : test_list = [(4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [(4, 5, 9)] Explanation : Extracted tuples with all positive elements. Input : test_list = [(-4, 5, 9), (-3, 2, 3), (-3, 5, 6), (4, -6)] Output : [] Explanation : No tuple wit
10 min read
Python program to find tuples which have all elements divisible by K from a list of tuples
Given a list of tuples. The task is to extract all tuples which have all elements divisible by K. Input : test_list = [(6, 24, 12), (60, 12, 6), (12, 18, 21)], K = 6 Output : [(6, 24, 12), (60, 12, 6)] Explanation : Both tuples have all elements multiple of 6. Input : test_list = [(6, 24, 12), (60, 10, 5), (12, 18, 21)], K = 5 Output : [(60, 10, 5)
7 min read
Practice Tags :
three90RightbarBannerImg