Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Filter tuple with all same elements
When it is required to filter out tuples that contain only identical elements, a list comprehension combined with the set function and len method can be used. This approach leverages the fact that a set of identical elements has length 1.
How It Works
The filtering logic works by converting each tuple to a set. Since sets contain only unique elements, a tuple with all identical elements will produce a set of length 1.
Example
Below is a demonstration of filtering tuples with all same elements ?
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)]
Alternative Methods
Using all() Function
You can also use the all() function to check if all elements are equal to the first element ?
my_list = [(31, 54, 45, 11, 99), (11, 11), (45, 45, 45), (99, 99), (0, 0)]
my_result = [tup for tup in my_list if len(tup) > 0 and all(x == tup[0] for x in tup)]
print("Filtered tuples:")
print(my_result)
Filtered tuples: [(11, 11), (45, 45, 45), (99, 99), (0, 0)]
Explanation
A list of tuples is defined and displayed on the console.
List comprehension iterates over each tuple in the list.
The condition
len(set(sub_list)) == 1checks if all elements are identical by converting the tuple to a set.If the set has only one unique element, the tuple passes the filter.
The filtered tuples are stored in a new list and displayed as output.
Conclusion
Using len(set(tuple)) == 1 is the most efficient way to filter tuples with identical elements. The all() function provides a readable alternative for the same task.
