Remove similar element rows in tuple Matrix in Python

PythonServer Side ProgrammingProgramming

When it is required to remove similar element rows in a tuple matrix, the list comprehension and the 'all' method can be used.

The list comprehension is a shorthand to iterate through the list and perform operations on it.

The 'all' method checks to see if all the values inside an iterable are True values. If yes, it returns True, else returns False.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = ((11, 14, 0), (78, 33, 11), (10, 78, 0), (78,78,78))

print("The tuple of tuples is : ")
print(my_tuple_1)

my_result = tuple(ele for ele in my_tuple_1 if not all(sub == ele[0] for sub in ele))

print("The tuple after removing like-element rows is: ")
print(my_result)

Output

The tuple of tuples is :
((11, 14, 0), (78, 33, 11), (10, 78, 0), (78, 78, 78))
The tuple after removing like-element rows is:
((11, 14, 0), (78, 33, 11), (10, 78, 0))

Explanation

  • A nested tuple is defined and is displayed on the console.
  • The tuple is iterated over, and the 'all' method is called on every element of the nested tuple.
  • It is then converted into a tuple.
  • This is assigned to a value.
  • It is displayed on the console.
raja
Updated on 12-Mar-2021 05:53:28

Advertisements