The Wayback Machine - https://web.archive.org/web/20240927080002/https://www.geeksforgeeks.org/python-remove-empty-tuples-list/
Open In App

Python | Remove empty tuples from a list

Last Updated : 19 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 | 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 | Remove and print every third from list until it becomes empty
Given a list of numbers, Your task is to remove and print every third number from a list of numbers until the list becomes empty. Examples: Input : [10, 20, 30, 40, 50, 60, 70, 80, 90] Output : 30 60 90 40 80 50 20 70 10 Explanation: The first third element encountered is 30, after 30 we start the count from 40 for the next third element which is 6
4 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python - Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be an empty string, empty list, dictionary, or even 0. This has applications in data preprocessing. Let us discuss certain ways in which this ta
7 min read
How to remove empty tags using BeautifulSoup in Python?
Prerequisite: Requests, BeautifulSoup, strip The task is to write a program that removes the empty tag from HTML code. In Beautiful Soup there is no in-built method to remove tags that has no content. Module Needed:bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python
2 min read
Remove all empty files within a folder and subfolders in Python
In this article, we will see how to remove all empty files within a folder and its subfolders in Python. We occasionally produce some empty files that are not needed. Here, we will use the below functions/methods to remove all empty files within a folder and its subfolder imported from the OS module and glob module. MethodDescriptionos.walk(path)Ge
4 min read
Remove Empty Dates from X Axis using Python Plotly
Plotly is a powerful graphing library that makes interactive, publication-quality graphs online using Python. One common task when creating time series plots is to remove empty dates from the x-axis, making the plot cleaner and more readable. In this article, we will go through the process of removing empty dates from the x-axis using Plotly. Key c
4 min read
Python | Convert a list of Tuples into Dictionary
Sometimes you might need to convert a tuple to dict object to make it more readable. In this article, we will try to learn how to convert a list of tuples into a dictionary. Here we will find two methods of doing this. Examples: Input : [("akash", 10), ("gaurav", 12), ("anand", 14), ("suraj", 20), ("akhil", 25), ("ashish", 30)] Output : {'akash': [
6 min read
Python | Unzip a list of tuples
The zipping technique, that is assigning a key value or pairing from two different lists has been covered in many articles before, sometimes we have a specific utility to perform the reverse task. This task can be achieved by various methods. Let's discuss some of the methods to unzip a list of tuples. Method #1: Using List comprehension Using list
5 min read
Python | Accessing nth element from tuples in list
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem. Method #1 : Using list comprehe
8 min read
Python | Linear search on list or tuples
Let us see a basic linear search operation on Python lists and tuples. A simple approach is to do a linear search, that is Start from the leftmost element of the list and one by one compare x with each element of the list.If x matches with an element, return True.If x doesn’t match with any of the elements, return False. Example #1: Linear Search o
2 min read
Python | Position Summation in List of Tuples
Sometimes the data that we receive is in the form of tuples having data from various sources and we can usually have a use case in which we require to process the sum of each index of tuple for cumulation. Let's discuss certain ways in which this can be performed. Method #1: Using list comprehension This is the most naive method to perform this par
7 min read
Python | Preceding element tuples in list
Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the preceding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let's discuss a way in which this task can be performed. Method #1: Using for loop C/C++ Code # Python3 c
5 min read
How we can iterate through list of tuples in Python
In this article, we will discuss different ways to iterate the list of tuples in Python. It can be done in these ways: Using Loop.Using enumerate().Method 1: Using Loop Here we are going to form a list of tuples using for loop. C/C++ Code # create a list of tuples with student # details name = [('sravan',7058,98.45), ('ojaswi',7059,90.67), ('bobby'
2 min read
Python Memory Consumption: Dictionary VS List of Tuples
In this article, we are going to see memory consumption in dictionaries and a list of tuples. Memory Consumption by dict vs list of tuples Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory
4 min read
Python - Create a List of Tuples
List and tuples both are data structures in Python, with some differences. Lists are mutable data structures whereas tuples are immutable (can not be changed after creating it). We can make a list that contains tuples as elements. This practice is useful for data structuring, memory efficiency, and data security as tuples are immutable. In this art
4 min read
Convert List Of Tuples To Json Python
Working with data often involves converting between different formats, and JSON is a popular choice for data interchange due to its simplicity and readability. In Python, converting a list of tuples to JSON can be achieved through various approaches. In this article, we'll explore four different methods, each offering its own advantages in differen
3 min read
Python: Get List of all empty Directories
The OS module in Python is used for interacting with the operating system. This module comes with Python's standard utility module so there is no need to install it externally. All functions in the OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted
2 min read
IndexError: pop from Empty List in Python
The IndexError: pop from an empty list is a common issue in Python, occurring when an attempt is made to use the pop() method on a list that has no elements. This article explores the nature of this error, provides a clear example of its occurrence, and offers three practical solutions to handle it effectively. Here, we will see how to fix Pop From
3 min read
Declare an empty List in Python
Lists are just like arrays, declared in other languages. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain data types like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation. However, Have you ever wondered about how to decl
4 min read
Python - Check if a list is empty or not
In Python programming, determining whether a list is empty holds importance for effective data handling. This article delves into concise techniques for checking the emptiness of a list, enabling developers to efficiently validate if a list contains elements or is devoid of data. Through clear code examples, learn how to implement these methods and
7 min read
Create PySpark DataFrame from list of tuples
In this article, we are going to discuss the creation of a Pyspark dataframe from a list of tuples. To do this, we will use the createDataFrame() method from pyspark. This method creates a dataframe from RDD, list or Pandas Dataframe. Here data will be the list of tuples and columns will be a list of column names. Syntax: dataframe = spark.createDa
2 min read
Convert PySpark dataframe to list of tuples
In this article, we are going to convert the Pyspark dataframe into a list of tuples. The rows in the dataframe are stored in the list separated by a comma operator. So we are going to create a dataframe by using a nested list Creating Dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sq
2 min read
Creating a Pandas dataframe using list of tuples
Pandas is famous for data manipulation in Python. We can create a DataFrame from a list of simple tuples, and can even choose the specific elements of the tuples we want to use. Using pd.DataFrame() functionHere we will create a Pandas Dataframe using a list of tuples with the pd.DataFrame() function. Example 1: In this example, we will simply pass
2 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Set 3 (Strings, Lists, Tuples, Iterations)
In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quotes, or even triple quotes. These quotes are not a
3 min read
Tuples in Python
Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable. Creating Python TuplesThere are various ways by which you can create a tuple i
6 min read
Python | Sort Tuples in Increasing Order by any key
Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)] E
3 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Python | Filter dictionary of tuples by condition
Sometimes, we can have a very specific problem in which we are given a tuple pair as values in dictionary and we need to filter dictionary items according to those pairs. This particular problem as use case in Many geometry algorithms in competitive programming. Let's discuss certain ways in which this task can be performed. Method #1 : Using items
3 min read
Practice Tags :