logo CodeStepByStep logo


Language/Type: Python lists list programming

Write a function named num_unique that accepts a sorted list of integers as a parameter and that returns the number of unique values in the list. The list is guaranteed to be in sorted order, which means that duplicates will be grouped together. For example, if a variable called lst stores the following values:

lst = [5, 7, 7, 7, 8, 22, 22, 23, 31, 35, 35, 40, 40, 40, 41]

then the call of num_unique(lst) should return 9 because this list has 9 unique values (5, 7, 8, 22, 23, 31, 35, 40 and 41). It is possible that the list might not have any duplicates. For example if list instead stored this sequence of values:

lst = [1, 2, 11, 17, 19, 20, 23, 24, 25, 26, 31, 34, 37, 40, 41]

Then a call on the function would return 15 because this list contains 15 different values.

If passed an empty list, your function should return 0. Remember that you can assume that the values in the list appear in sorted (nondecreasing) order.

Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.