
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Tuples from List Having All Elements as None in Python
When it is required to remove tuples from a list of tuples where a ‘None’ element is present, a list comprehension can be used.
Below is a demonstration of the same −
Example
my_list = [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None, ), (None, 45, 6)] print("The list is : ") print(my_list) my_result = [sub for sub in my_list if not all(elem == None for elem in sub)] print("The None tuples have been removed, the result is : " ) print(my_result)
Output
The list is : [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None,), (None, 45, 6)] The None tuples have been removed, the result is : [(2, None, 12), (23, 64), (121, 13), (None, 45, 6)]
Explanation
A list of tuple is defined, and is displayed on the console.
The list comprehension is used to iterate over the list.
The ‘all’ condition is used to see if there are ‘None’ elements.
When ‘None’ elements are present, they are filtered out.
The remaining data is assigned to a variable.
This variable is displayed as the output.
Advertisements