
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
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.
- Related Articles
- Python – Filter rows with required elements
- Python – Filter Rows with Range Elements
- Find whether all tuple have same length in Python
- Python – Elements with same index
- Program to find tuple with same product in Python
- Python – Filter rows with Elements as Multiple of K
- Python – Filter consecutive elements Tuples
- Count occurrence of all elements of list in a tuple in Python
- Delete Tuple Elements in Python
- Python – Rows with all List elements
- Python - Check if all elements in a List are same
- Modulo of tuple elements in Python
- Tuple with the same Product in C++
- Raise elements of tuple as power to another tuple in Python
- How to append elements in Python tuple?

Advertisements