w3resource

Python: Function that takes a sequence of numbers and determines whether all are different from each other

Python Basic - 1: Exercise-1 with Solution

Unique Numbers Check

Write a Python function that takes a sequence of numbers and determines whether all the numbers are different from each other.

Visual Presentation:

Python: Function that takes a sequence of numbers and determines whether all  are different from each other

Sample Solution:

Python Code :

# Define a function named test_distinct that takes a list 'data' as a parameter.
def test_distinct(data):
    # Check if the length of the list is equal to the length of the set created from the list.
    if len(data) == len(set(data)):
        # If the lengths are equal, it means all elements in the list are distinct.
        return True
    else:
        # If the lengths are not equal, there are duplicate elements in the list.
        return False

# Call the test_distinct function with a list [1, 5, 7, 9] and print the result.
print(test_distinct([1, 5, 7, 9]))

# Call the test_distinct function with a list [2, 4, 5, 5, 7, 9] and print the result.
print(test_distinct([2, 4, 5, 5, 7, 9]))

Sample Output:

True
False

Explanation:

The above code defines a function "test_distinct()" that takes a list as input. It checks if the length of the list is equal to the length of the set created from the list.

  • If they are equal, it means all elements in the list are distinct, and the function returns 'True'.
  • Otherwise, it returns 'False' indicating the presence of duplicate elements.

The code then calls this function with two different lists and prints the results.

Flowchart:

Flowchart: Python - Function that takes a sequence of numbers and determines whether all  are different from each other

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Basic - Part-I.
Next: Write a Python program to create all possible strings by using 'a', 'e', 'i', 'o', 'u'. Use the characters exactly once.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/basic/python-basic-1-exercise-1.php