- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Filter tuple with all same elements
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.
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)
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)]
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.
- Find whether all tuple have same length in Python
- Python – Filter rows with required elements
- Python – Filter Rows with Range Elements
- Python – Elements with same index
- Program to find tuple with same product in Python
- Python - Check if all elements in a List are same
- Tuple with the same Product in C++
- Delete Tuple Elements in Python
- Python – Filter consecutive elements Tuples
- Python – Filter rows with Elements as Multiple of K
- Count occurrence of all elements of list in a tuple in Python
- Python – Rows with all List elements
- Modulo of tuple elements in Python
- How to append elements in Python tuple?
- Python - Join tuple elements in a list