Removing empty tuples from a list in Python
In this article, we are gonna see how to remove empty tuples from a list in Python. We will see two ways through which we can remove empty tuples from the list in Python. It is simple to understand, so let’s get started.
First, let us see what are we gonna do through an example:
Input:
[(), ('okay','10','11'), (), ('lock', 'key'), ('kite', '12'),()]
Output:
[('okay', '10', '11'), ('lock', 'key'), ('kite', '12')]
Here are the methods to remove empty tuples from a list in Python:
Using List Comprehension:
In this method, we are going to use the concept of List Comprehension to remove empty tuples from the list in Python.
You can read about List Comprehension here: List and dictionary comprehension in python
# Removing empty tuples # using list comprehension def without(tuples): tuples = [t for t in tuples if t] return tuples # driver code tuples = [(), ('okay','10','11'), (), ('lock', 'key'), ('kite', '12'),()] print(without(tuples))
OUTPUT: [(‘okay’, ’10’, ’11’), (‘lock’, ‘key’), (‘kite’, ’12’)]
Using the filter() method:
In this method, we going to use the filter( ) method to remove empty tuples from the list in Python.
So, let’s see how this method gonna work:
# Removing empty tuples # using filter() method list_1 = [(), ('okay','10','11'), (), ('lock', 'key'), ('kite', '12'),()] filter_items = filter(lambda x: x != (), list_1) remove_tuples = list(filter_items) print(remove_tuples)
OUTPUT:
[('okay', '10', '11'), ('lock', 'key'), ('kite', '12')]
Screenshot:
Therefore, we have learned how to remove empty tuples from a list in Python!
Leave a Reply