Given a list, print all the unique numbers in any order.
Examples:
Method 1 : Traversal of list
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Using traversal, we can traverse for every element in the list and check if the element is in the unique_list already if it is not over there, then we can append it in the unique_list. This is done using one for loop and other if statement which check if the value is in the unique list or not which is equivalent to another for loop.
Output:
the unique values from 1st list is 10 20 30 40 the unique values from 2nd list is 1 2 3 4 5Method 2 : Using Set
Using set() property of Python, we can easily check for the unique values. Insert the values of the list in a set. Set only stores a value once even if it is inserted more then once. After inserting all the values in the set by list_set=set(list1), convert this set to a list to print it.
Output:
the unique values from 1st list is 40 10 20 30 the unique values from 2nd list is 1 2 3 4 5Method 3 : Using numpy.unique
Using Pythons import numpy, the unique elements in the array are also obtained. In first step convert the list to x=numpy.array(list) and then use numpy.unique(x) function to get the unique values from the list. numpy.unique() returns only the unique values in the list.
Output
Method #4: Using collections.Counter()
Using python import Counter() from collections print all the keys of Counter elements or we print directly by using * symbol.
Below is the implementation of above approach.
Output:
the unique values from 1st list is 10 20 30 40 the unique values from 2nd list is 1 2 3 4 5