Python – Filter tuple with all same elements

PythonServer Side ProgrammingProgramming

When it is required to filter out the tuple that contains same elements, a list comprehension and the ‘set’ operator and the ‘len’ methods can be used.

Example

Below is a demonstration of the same −

my_list = [(31, 54, 45, 11, 99) , (11,11), (45, 45, 45), (31, 54, 45, 11, 99),(99, 99), (0,0)]

print("The list is : " )
print(my_list)

my_result = [sub_list for sub_list in my_list if len(set(sub_list)) == 1]

print("The resultant list is : ")
print(my_result)

Output

The list is :
[(31, 54, 45, 11, 99), (11, 11), (45, 45, 45), (31, 54, 45, 11, 99), (99, 99), (0, 0)]
The resultant list is :
[(11, 11), (45, 45, 45), (99, 99), (0, 0)]

Explanation

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

  • A list comprehension is used to iterate over the elements in the list.

  • A condition is placed that checks to see if the length of the elements in the list, after applying the ‘set’ operator on them is equal to 1.

  • If yes, it is stored in a list.

  • This list is assigned to a variable.

  • It is displayed as output on the console.

raja
Updated on 13-Sep-2021 11:22:26

Advertisements