- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- 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 −
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)
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']
- 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.
Kickstart Your Career
Get certified by completing the courseGet Started