Iterate through the same list twice to find no duplicate numbers

Here is my code below

*Testing lists below*
a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]
***

def is_unique(a_list): #returns true for no duplicate numbers #returns false other wise
    for num1 in a_list: #iterate through list once
        for num2 in a_list: #iterate thorough list twice
            if num1 == num2: #if num1 is the same as num2
                return False
            else:         #if num1 is not the same as num2
                return True

I want to show that the is_unique function can iterate through the same list twice and if the list has no duplicate numbers then it returns True Every time I run it I only get false, I can't get a True statement

I don't want to use sets

Answers 1

  • Convert the list to set and compare numbers from the set and the list.

    a = [9, 4, 2, 3, 5, 9, 10]
    b = [3, 4, -1, 9, 99, 12, 34]
    
    def is_unique(a_list):
        a_list_len = len(a_list)
        a_set_len = len(set(a_list))
        return a_list_len == a_set_len
    
    print(is_unique(a))
    print(is_unique(b))
    

    The output:

    False
    True
    

    A solution without using set:

    def is_unique(a_list):
        for a in a_list:
            if a_list.count(a) > 1:
                return False
        else:
            return True
    
    print(is_unique(a))
    print(is_unique(b))
    

    The output:

    False
    True
    

Related Articles