Friday, 24 September 2021

Python: How to find unique numbers in a list

Approach 1: Traverse the list and add the element to the unique_list, if not exists.

 

unique_elements_1.py

def unique_elements(my_list):
    unique_list = []

    for item in my_list:
        if item not in unique_list:
            unique_list.append(item)

    return unique_list

numbers = [1, 2, 3, 4, 2, 3, 4, 5]
unique_numbers = unique_elements(numbers)

print('numbers -> ', numbers)
print('unique_numbers -> ', unique_numbers)

Output

numbers ->  [1, 2, 3, 4, 2, 3, 4, 5]
unique_numbers ->  [1, 2, 3, 4, 5]


Approach 2: By adding the elements to a set. Since set store only unique elements, we can use this behaviour to get unique elements.

 

unique_elements_2.py

def unique_elements(my_list):
    return list(set(my_list))
    
numbers = [1, 2, 3, 4, 2, 3, 4, 5]
unique_numbers = unique_elements(numbers)

print('numbers -> ', numbers)
print('unique_numbers -> ', unique_numbers)


Output

numbers ->  [1, 2, 3, 4, 2, 3, 4, 5]
unique_numbers ->  [1, 2, 3, 4, 5]



  

Previous                                                    Next                                                    Home

No comments:

Post a Comment