Python – Remove Tuples from a List having every element as None

PythonServer Side ProgrammingProgramming

When it is required to remove tuples from a list having every element as None, a list comprehension and the ‘all’ operator is used.

Below is a demonstration of the same −

Example

 Live Demo

my_tuple = [(None, 12), (None, None), (33, 54), (32, 13), (None, )]

print("The tuple is :")
print(my_tuple)

my_result = [index for index in my_tuple if not all(element == None for element in index)]

print("The result is :")
print(my_result)

Output

The tuple is :
[(None, 12), (None, None), (33, 54), (32, 13), (None,)]
The result is :
[(None, 12), (33, 54), (32, 13)]

Explanation

  • A list of tuple is defined and displayed on the console.

  • A list comprehension is used to iterate over the list, and the elements are checked to be equivalent to ‘None’.

  • Only if not all the elements are ‘None’, it is added to a list and is assigned to a variable.

  • All elements are checked since ‘all’ operator and ‘not’ operator are used.

  • This result is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Published on 06-Sep-2021 08:53:13
Advertisements