Remove Tuples from the List having every element 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

 Live Demo

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.

Updated on: 15-Apr-2021

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements