Active September 23, 2021    /    Viewed 3169    /    Comments 0    /    Edit

Examples of how to get unique values in a list in python:

Create a list in python

Let's first create a list with unique values:

mylist1 = ['a', 'b', 'c', 'd']

and then create another bigger list using those unique values:

import random

mylist2 = [random.choice(mylist1) for i in range(20)]

mylist2

gives for example:

['d',
'c',
'd',
'd',
'b',
'd',
'a',
'b',
'b',
'd',
'a',
'b',
'a',
'b',
'a',
'd',
'b',
'd',
'a',
'b']

Goal: get unique values from mylist2.

Get unique values in a list

There are several solutions to do that.

Convert the list into a set

A straightforward solution is to convert the list into a set (see Data Structures):

mylist2 = set(mylist2)

and to convert again into a list

mylist2 = list(mylist2)

print(mylist2)

gives

['d', 'a', 'b', 'c']

Note: to sort the list:

mylist2.sort()

print(mylist2)

gives then

['a', 'b', 'c', 'd']

Convert the list into a matrix

Another solution is to convert into a matrix

import numpy as np

mylist2 = np.array(mylist2)

since numpy as the function unique()

mylist2 = np.unique(mylist2)

and convert again into a list

mylist2 = list(mylist2)

mylist2

gives

['a', 'b', 'c', 'd']

Iterate over each value with a for loop

Another solution is to simply iterate over each value with a for loop

mylist3 = []

for i in mylist2:
if i not in mylist3:
mylist3.append(i)

mylist2 = mylist3

mylist2.sort()

print(mylist2)

gives

['a', 'b', 'c', 'd']  Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!

Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount