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
Selected Reading
Test if tuple is distinct in Python
When it is required to test if a tuple has distinct elements in it, the set method and the len method can be used.
Python comes with a datatype known as set. This set contains elements that are unique only. The len method gives the length of the parameter passed to it.
Method 1: Using set() and len()
Convert the tuple to a set and compare lengths. If they are equal, all elements are distinct ?
my_tuple = (11, 14, 54, 0, 58, 41)
print("The tuple is:")
print(my_tuple)
is_distinct = len(set(my_tuple)) == len(my_tuple)
print("Is the tuple distinct?")
print(is_distinct)
The tuple is: (11, 14, 54, 0, 58, 41) Is the tuple distinct? True
Method 2: Testing with Duplicate Elements
Let's test with a tuple that contains duplicate elements ?
my_tuple = (11, 14, 54, 11, 58, 41)
print("The tuple is:")
print(my_tuple)
is_distinct = len(set(my_tuple)) == len(my_tuple)
print("Is the tuple distinct?")
print(is_distinct)
The tuple is: (11, 14, 54, 11, 58, 41) Is the tuple distinct? False
How It Works
The algorithm works by:
- Converting the tuple to a set, which removes all duplicate elements
- Comparing the length of the original tuple with the length of the set
- If lengths are equal, all elements were unique (distinct)
- If lengths differ, there were duplicate elements
Alternative Method: Using Loop
You can also check for distinct elements using a loop ?
def is_tuple_distinct(my_tuple):
seen = set()
for element in my_tuple:
if element in seen:
return False
seen.add(element)
return True
my_tuple = (11, 14, 54, 0, 58, 41)
print("The tuple is:")
print(my_tuple)
result = is_tuple_distinct(my_tuple)
print("Is the tuple distinct?")
print(result)
The tuple is: (11, 14, 54, 0, 58, 41) Is the tuple distinct? True
Conclusion
Use len(set(tuple)) == len(tuple) for a simple one-liner to check if a tuple has distinct elements. The set method is efficient and readable for this common task.
Advertisements
