Test if tuple is distinct in Python

PythonServer Side ProgrammingProgramming

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.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (11, 14, 54, 0, 58, 41)

print("The tuple is : ")
print(my_tuple_1)

my_result = len(set(my_tuple_1)) == len(my_tuple_1)

print("Is the tuple distinct ? ")
print(my_result)

Output

The tuple is :
(11, 14, 54, 0, 58, 41)
Is the tuple distinct ?
True

Explanation

  • A tuple is defined and is displayed on the console.
  • The tuple is converted to a set, and its length, and the length of the original tuple is determined.
  • These two are checked using the '==' operator.
  • This is assigned to a value.
  • It is displayed on the console.
raja
Published on 12-Mar-2021 10:16:13
Advertisements