- 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 Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
- 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?