ID : 338
viewed : 59
Tags : PythonPython List
97
This tutorial discusses methods to get unique values from a list in Python.
dict.fromkeys
to Get Unique Values From a List in PythonWe can use the dict.fromkeys
method of the dict
class to get unique values from a Python list. This method preserves the original order of the elements and keeps only the first element from the duplicates. The below example illustrates this.
inp_list = [2, 2, 3, 1, 4, 2, 5] unique_list = list(dict.fromkeys(inp_list)) print(unique_list)
Output:
[2, 3, 1, 4, 5]
Another method to get unique values from a list in Python is to create a new list and add only unique elements to it from the original list. This method preserves the original order of the elements and keeps only the first element from the duplicates. The below example illustrates this.
inp_list = [2, 2, 3, 1, 4, 2, 5] unique_list = [] [unique_list.append(x) for x in inp_list if x not in unique_list] unique_list
Output:
[2, 3, 1, 4, 5]
set()
to Get Unique Values From a List in PythonSet
in Python holds unique values only. We can insert the values from our list to a set
to get unique values. However, this method does not preserve the order of the elements. The below example illustrates this.
inp_list = [2, 2, 3, 1, 4, 2, 5] unique_list = list(set(inp_list)) print(unique_list)
Output:
[1, 2, 3, 4, 5]
Note that the order of elements is not preserved as in the original list.