- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements