To get the unique items of a list in Python, the easiest way is by converting the list to a set with set() and then back to a list with list().

l = [0,7,7,7,0,2,3,1,1,4,5,6,7]

l_unique = list(set(l))

print(l_unique)

#Output:
[0,1,2,3,4,5,6,7]

If need to preserve the order of the elements in the list, then you can use comprehension to obtain a unique list.

l = [0,7,7,7,0,2,3,1,1,4,5,6,7]

l_unique = []

[l_unique.append(x) for x in l if x not in l_unique]

print(l_unique)

#Output:
[0, 7, 2, 3, 1, 4, 5, 6]

When working with collections of data in Python, the ability to get the unique values of your data is valuable.

To get the unique values of a list in Python, the easiest way is by converting the list to a set with set() and then back to a list with list().

A set is an unordered collection of unique elements. On the other hand, lists are ordered and can contain duplicates.

Converting a list to a set creates a set with the same items as the list and returns a unique list.

Below is how to get the unique values from a list with the set() function in Python.

l = [0,7,7,7,0,2,3,1,1,4,5,6,7]

l_unique = list(set(l))

print(l_unique)

#Output:
[0,1,2,3,4,5,6,7]

Obtaining Unique Values of List and Preserving Order of Elements in Python

If need to preserve the order of the elements in the list, then we need to do a little more work.

When converting a list to a set, the duplicates of the list are removed and also sorted.

To preserve the order of the elements in the list, you need to use a loop. To loop in Python, you can use comprehension or a standard for loop.

The process here to preserve the order of the elements of the original list is to create a second list.

We will append items to the second list if they aren’t already in the second list and this will preserve the order of the original list.

Below shows you how to obtain a unique list of values from a list and preserve the order of the elements with comprehension in Python.

l = [0,7,7,7,0,2,3,1,1,4,5,6,7]

l_unique = []

[l_unique.append(x) for x in l if x not in l_unique]

print(l_unique)

#Output:
[0, 7, 2, 3, 1, 4, 5, 6]

This is the same as the following for loop.

l = [0,7,7,7,0,2,3,1,1,4,5,6,7]

l_unique = []

for x in l:
    if x not in l_unique: 
        l_unique.append(x)

print(l_unique)

#Output:
[0, 7, 2, 3, 1, 4, 5, 6]

Hopefully this article has been useful for you to create a unique list from a list in Python.

Categorized in:

Python,

Last Update: March 11, 2024