Как найти уникальные значения в списке python

Предположим, есть список, который содержит повторяющиеся числа:

numbers = [1, 1, 2, 3, 3, 4]

Но нужен список с уникальными числами:

numbers = [1, 2, 3, 4]

Есть несколько вариантов, как можно получить уникальные значения. Разберем их.

Вариант №1. Использование множества (set) для получения элементов

Использование множества (set) — один из вариантов. Он удобен тем, что включает только уникальные элементы. После этого множество можно обратно превратить в список.

Посмотрим на два способа использования множества и списка. Первый — достаточно подробный, но он позволяет увидеть происходящее на каждом этапе.


numbers = [1, 2, 2, 3, 3, 4, 5]

def get_unique_numbers(numbers):
list_of_unique_numbers = []
unique_numbers = set(numbers)

for number in unique_numbers:
list_of_unique_numbers.append(number)

return list_of_unique_numbers

print(get_unique_numbers(numbers))

Разберем, что происходит на каждом этапе. Есть список чисел numbers. Передаем его в функцию get_unique_numbers.

Внутри этой функции создается пустой список, который в итоге будет включать все уникальные числа. После этого используется set для получения уникальных чисел из списка numbers.


unique_numbers = set(numbers)

В итоге имеется перечень из уникальных чисел. Осталось сделать из него список. Для этого можно использовать цикл, перебирая каждый из элементов.


for number in unique_numbers:
list_of_unique_numbers.append(number)

На каждой итерации текущее число добавляется в список list_of_unique_numbers. Наконец, именно этот список возвращается в конце программы.

Есть и более короткий способ использования множества для получения уникальных значений в Python. О нем и пойдет речь дальше.

Короткий вариант с set

Весь код выше можно сжать в одну строку с помощью встроенных в Python функций.


numbers = [1, 2, 2, 3, 3, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)

Хотя этот код сильно отличается от первого примера, идея та же. Сперва множество используется для получения уникальных значений. После этого множество превращается в список.


unique_numbers = list(set(numbers))

Проще всего думать «изнутри наружу» при чтении этого кода. Самый вложенный код выполняется первым: set(numbers). Затем — внешний блок: list(set(numbers)).

Вариант №2. Использование цикла for

Также стоит рассмотреть подход с использованием цикла.

Для начала нужно создать пустой список, который будет включать уникальные числа. После этого можно задействовать цикл для итерации по каждому числу в переданном списке. Если число из него есть в уникальном, то можно переходить к следующему элементу. В противном случае — добавить это число.

Рассмотрим два способа использования цикла. Начнем с более подробного.


numbers = [20, 20, 30, 30, 40]

def get_unique_numbers(numbers):
unique = []

for number in numbers:
if number in unique:
continue
else:
unique.append(number)
return unique

print(get_unique_numbers(numbers))

Вот что происходит на каждом этапе. Сначала есть список чисел numbers. Он передается в функцию get_unique_numbers.

Внутри этой функции создается пустой список unique. В итоге он будет включать все уникальные значения.

Цикл будет использоваться для перебора по числам в списке numbers.


for number in numbers:
if number in unique:
continue
else:
unique.append(number)

Условные конструкции в цикле проверяют, есть ли число текущей итерации в списке unique. Если да, то цикл переходит на следующую итерации. Если нет — число добавляется в список.

Важно отметить, что добавляются только уникальные числа. Когда цикл завершен, список unique с уникальными числами возвращается.

Короткий способ с циклом

Есть и другой способ использования варианта с циклом, который короче на несколько строк.


numbers = [20, 20, 30, 30, 40]

def get_unique_numbers(numbers):
unique = []
for number in numbers:
if number not in unique:
unique.append(number)
return unique

Разница в условной конструкции. В этот раз она следующая — если числа нет в unique, то его нужно добавить.


if number not in unique:
unique.append(number)

В противном случае цикл перейдет к следующему числу в списке numbers.

Результат будет тот же. Но иногда подобное читать сложнее, когда булево значение опускается.

Есть еще несколько способов поиска уникальных значений в списке Python. Но достаточно будет тех, которые описаны в этой статье.

Given a list, print all the unique numbers in any order.

Examples: 

Input : 10 20 10 30 40 40
Output : 10 20 30 40 

Input : 1 2 1 1 3 4 3 3 5 
Output : 1 2 3 4 5  

Method 1: Traversal of the list

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 to the unique_list. This is done using one for loop and another if statement which checks if the value is in the unique list or not which is equivalent to another for a loop.  

Python

def unique(list1):

    unique_list = []

    for x in list1:

        if x not in unique_list:

            unique_list.append(x)

    for x in unique_list:

        print x,

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output

the unique values from 1st list is
10 20 30 40 
the unique values from 2nd list is
1 2 3 4 5

Time Complexity: O(n*n)
Auxiliary Space: O(n)

Method 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 than once. After inserting all the values in the set by list_set=set(list1), convert this set to a list to print it. 

Python

def unique(list1):

    list_set = set(list1)

    unique_list = (list(list_set))

    for x in unique_list:

        print x,

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output

the unique values from 1st list is
40 10 20 30 
the unique values from 2nd list is
1 2 3 4 5

Time complexity: O(n), where n is length of list.
Auxiliary Space: O(n), where n is length of list.

Method 3: Using numpy.unique

Using Python’s import numpy, the unique elements in the array are also obtained. In the 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. 

Python3

import numpy as np

def unique(list1):

    x = np.array(list1)

    print(np.unique(x))

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output: 

the unique values from 1st list is
[10 20 30 40]

the unique values from 2nd list is
[1 2 3 4 5]

Time complexity: O(nlogn) due to the use of the sorting algorithm used by the numpy.unique() function. 
Auxiliary space: O(n) because numpy.unique() function creates a copy of the input array and then sorts it before returning the unique elements. 

Method #4: Using collections.Counter()

Using python import Counter() from collections print all the keys of Counter elements or we print directly by using the “*” symbol. Below is the implementation of above approach.

Python3

from collections import Counter

def unique(list1):

    print(*Counter(list1))

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output

the unique values from 1st list is
10 20 30 40

the unique values from 2nd list is
1 2 3 4 5

Time Complexity: O(n), where n is the number of elements in the input list.
Auxiliary Space : O(n)

Method #5: Using reduce()

Using python import reduce() from functools and iterate over all element and checks if the element is a duplicate or unique value. Below is the implementation of the above approach.

Python

from functools import reduce

def unique(list1):

    ans = reduce(lambda re, x: re+[x] if x not in re else re, list1, [])

    print(ans)

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output

the unique values from 1st list is
[10, 20, 30, 40]

the unique values from 2nd list is
[1, 2, 3, 4, 5]

Method #6:Using Operator.countOf() method

Python3

import operator as op

def unique(list1):

    unique_list = []

    for x in list1:

        if op.countOf(unique_list, x) == 0:

            unique_list.append(x)

    for x in unique_list:

        print(x)

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output

the unique values from 1st list is
10
20
30
40

the unique values from 2nd list is
1
2
3
4
5

Time Complexity:O(N)
Auxiliary Space: O(N)

Method#7: Using pandas

Python3

import pandas as pd

def unique(list1):

    unique_list = pd.Series(list1).drop_duplicates().tolist()

    for x in unique_list:

        print(x)

list1 = [10, 20, 10, 30, 40, 40]

print("the unique values from 1st list is")

unique(list1)

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

print("nthe unique values from 2nd list is")

unique(list2)

Output:

the unique values from 1st list is
10
20
30
40

the unique values from 2nd list is
1
2
3
4
5

Time Complexity:O(N)
Auxiliary Space: O(N)

Method #8: Using dict.fromkeys() –

Using the fromkeys() method of dictionary data structure we can fetch the unique elements.

Step – 1: Firstly we need to define a list which consists of duplicate elements.

Step – 2 : Then we need to use a variable in which we will store the result after using the fromkeys() method.

Step – 3 : We need to convert that result into list, as the fromkeys() method is part of the dictionary so by default it returns a dictionary with all the unique keys and None as their values.

Step – 4 : We will print the final result.

Python3

list1 = [10, 20, 10, 30, 40, 40]

list2 = [1, 2, 1, 1, 3, 4, 3, 3, 5]

unique_list_1 = list(dict.fromkeys(list1))

unique_list_2 = list(dict.fromkeys(list2))

print(unique_list_1,unique_list_2,sep="n")

Output

[10, 20, 30, 40]
[1, 2, 3, 4, 5]

Time Complexity – O(n)
Space Complexity – O(n)

Last Updated :
15 May, 2023

Like Article

Save Article

What is the best way (best as in the conventional way) of checking whether all elements in a list are unique?

My current approach using a Counter is:

>>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2]
>>> counter = Counter(x)
>>> for values in counter.itervalues():
        if values > 1: 
            # do something

Can I do better?

Maciej Ziarko's user avatar

asked Mar 11, 2011 at 20:44

user225312's user avatar

user225312user225312

126k68 gold badges172 silver badges181 bronze badges

0

Not the most efficient, but straight forward and concise:

if len(x) > len(set(x)):
   pass # do something

Probably won’t make much of a difference for short lists.

answered Mar 11, 2011 at 20:47

yan's user avatar

5

Here is a two-liner that will also do early exit:

>>> def allUnique(x):
...     seen = set()
...     return not any(i in seen or seen.add(i) for i in x)
...
>>> allUnique("ABCDEF")
True
>>> allUnique("ABACDEF")
False

If the elements of x aren’t hashable, then you’ll have to resort to using a list for seen:

>>> def allUnique(x):
...     seen = list()
...     return not any(i in seen or seen.append(i) for i in x)
...
>>> allUnique([list("ABC"), list("DEF")])
True
>>> allUnique([list("ABC"), list("DEF"), list("ABC")])
False

answered Mar 12, 2011 at 9:12

PaulMcG's user avatar

PaulMcGPaulMcG

62k16 gold badges93 silver badges130 bronze badges

3

An early-exit solution could be

def unique_values(g):
    s = set()
    for x in g:
        if x in s: return False
        s.add(x)
    return True

however for small cases or if early-exiting is not the common case then I would expect len(x) != len(set(x)) being the fastest method.

answered Mar 11, 2011 at 20:50

6502's user avatar

65026502

111k15 gold badges164 silver badges265 bronze badges

4

for speed:

import numpy as np
x = [1, 1, 1, 2, 3, 4, 5, 6, 2]
np.unique(x).size == len(x)

answered Nov 29, 2012 at 20:29

jassinm's user avatar

jassinmjassinm

7,2633 gold badges33 silver badges42 bronze badges

How about adding all the entries to a set and checking its length?

len(set(x)) == len(x)

answered Mar 11, 2011 at 20:48

Grzegorz Oledzki's user avatar

Grzegorz OledzkiGrzegorz Oledzki

23.5k16 gold badges66 silver badges104 bronze badges

2

Alternative to a set, you can use a dict.

len({}.fromkeys(x)) == len(x)

answered Mar 11, 2011 at 20:50

Tugrul Ates's user avatar

Tugrul AtesTugrul Ates

9,4081 gold badge33 silver badges58 bronze badges

1

Another approach entirely, using sorted and groupby:

from itertools import groupby
is_unique = lambda seq: all(sum(1 for _ in x[1])==1 for x in groupby(sorted(seq)))

It requires a sort, but exits on the first repeated value.

answered Dec 27, 2012 at 4:34

PaulMcG's user avatar

PaulMcGPaulMcG

62k16 gold badges93 silver badges130 bronze badges

3

Here is a recursive O(N2) version for fun:

def is_unique(lst):
    if len(lst) > 1:
        return is_unique(s[1:]) and (s[0] not in s[1:])
    return True

answered Dec 14, 2014 at 5:51

Karol's user avatar

KarolKarol

1,2472 gold badges13 silver badges20 bronze badges

I’ve compared the suggested solutions with perfplot and found that

len(lst) == len(set(lst))

is indeed the fastest solution. If there are early duplicates in the list, there are some constant-time solutions which are to be preferred.

enter image description here

enter image description here


Code to reproduce the plot:

import perfplot
import numpy as np
import pandas as pd


def len_set(lst):
    return len(lst) == len(set(lst))


def set_add(lst):
    seen = set()
    return not any(i in seen or seen.add(i) for i in lst)


def list_append(lst):
    seen = list()
    return not any(i in seen or seen.append(i) for i in lst)


def numpy_unique(lst):
    return np.unique(lst).size == len(lst)


def set_add_early_exit(lst):
    s = set()
    for item in lst:
        if item in s:
            return False
        s.add(item)
    return True


def pandas_is_unique(lst):
    return pd.Series(lst).is_unique


def sort_diff(lst):
    return not np.any(np.diff(np.sort(lst)) == 0)


b = perfplot.bench(
    setup=lambda n: list(np.arange(n)),
    title="All items unique",
    # setup=lambda n: [0] * n,
    # title="All items equal",
    kernels=[
        len_set,
        set_add,
        list_append,
        numpy_unique,
        set_add_early_exit,
        pandas_is_unique,
        sort_diff,
    ],
    n_range=[2**k for k in range(18)],
    xlabel="len(lst)",
)

b.save("out.png")
b.show()

answered Jan 3 at 16:40

Nico Schlömer's user avatar

Nico SchlömerNico Schlömer

52.5k26 gold badges196 silver badges242 bronze badges

Here is a recursive early-exit function:

def distinct(L):
    if len(L) == 2:
        return L[0] != L[1]
    H = L[0]
    T = L[1:]
    if (H in T):
            return False
    else:
            return distinct(T)    

It’s fast enough for me without using weird(slow) conversions while
having a functional-style approach.

answered Apr 28, 2013 at 16:12

mhourdakis's user avatar

1

All answer above are good but I prefer to use all_unique example from 30 seconds of python

You need to use set() on the given list to remove duplicates, compare its length with the length of the list.

def all_unique(lst):
  return len(lst) == len(set(lst))

It returns True if all the values in a flat list are unique, False otherwise.

x = [1, 2, 3, 4, 5, 6]
y = [1, 2, 2, 3, 4, 5]
all_unique(x)  # True
all_unique(y)  # False

buhtz's user avatar

buhtz

10.3k17 gold badges73 silver badges145 bronze badges

answered Sep 12, 2019 at 12:37

ArunPratap's user avatar

ArunPratapArunPratap

4,7187 gold badges24 silver badges43 bronze badges

How about this

def is_unique(lst):
    if not lst:
        return True
    else:
        return Counter(lst).most_common(1)[0][1]==1

answered Nov 8, 2012 at 9:03

yilmazhuseyin's user avatar

yilmazhuseyinyilmazhuseyin

6,3824 gold badges33 silver badges38 bronze badges

If and only if you have the data processing library pandas in your dependencies, there’s an already implemented solution which gives the boolean you want :

import pandas as pd
pd.Series(lst).is_unique

answered Mar 18, 2022 at 16:59

Tom's user avatar

You can use Yan’s syntax (len(x) > len(set(x))), but instead of set(x), define a function:

 def f5(seq, idfun=None): 
    # order preserving
    if idfun is None:
        def idfun(x): return x
    seen = {}
    result = []
    for item in seq:
        marker = idfun(item)
        # in old Python versions:
        # if seen.has_key(marker)
        # but in new ones:
        if marker in seen: continue
        seen[marker] = 1
        result.append(item)
    return result

and do len(x) > len(f5(x)). This will be fast and is also order preserving.

Code there is taken from: http://www.peterbe.com/plog/uniqifiers-benchmark

answered Mar 11, 2011 at 20:51

canisrufus's user avatar

canisrufuscanisrufus

6551 gold badge6 silver badges19 bronze badges

1

Using a similar approach in a Pandas dataframe to test if the contents of a column contains unique values:

if tempDF['var1'].size == tempDF['var1'].unique().size:
    print("Unique")
else:
    print("Not unique")

For me, this is instantaneous on an int variable in a dateframe containing over a million rows.

answered Apr 19, 2016 at 22:38

user1718097's user avatar

user1718097user1718097

4,07011 gold badges48 silver badges62 bronze badges

It does not fully fit the question but if you google the task I had you get this question ranked first and it might be of interest to the users as it is an extension of the quesiton. If you want to investigate for each list element if it is unique or not you can do the following:

import timeit
import numpy as np

def get_unique(mylist):
    # sort the list and keep the index
    sort = sorted((e,i) for i,e in enumerate(mylist))
    # check for each element if it is similar to the previous or next one    
    isunique = [[sort[0][1],sort[0][0]!=sort[1][0]]] + 
               [[s[1], (s[0]!=sort[i-1][0])and(s[0]!=sort[i+1][0])] 
                for [i,s] in enumerate (sort) if (i>0) and (i<len(sort)-1) ] +
               [[sort[-1][1],sort[-1][0]!=sort[-2][0]]]     
    # sort indices and booleans and return only the boolean
    return [a[1] for a in sorted(isunique)]


def get_unique_using_count(mylist):
     return [mylist.count(item)==1 for item in mylist]

mylist = list(np.random.randint(0,10,10))
%timeit for x in range(10): get_unique(mylist)
%timeit for x in range(10): get_unique_using_count(mylist)

mylist = list(np.random.randint(0,1000,1000))
%timeit for x in range(10): get_unique(mylist)
%timeit for x in range(10): get_unique_using_count(mylist)

for short lists the get_unique_using_count as suggested in some answers is fast. But if your list is already longer than 100 elements the count function takes quite long. Thus the approach shown in the get_unique function is much faster although it looks more complicated.

answered Nov 29, 2021 at 14:15

horseshoe's user avatar

horseshoehorseshoe

1,41714 silver badges39 bronze badges

If the list is sorted anyway, you can use:

not any(sorted_list[i] == sorted_list[i + 1] for i in range(len(sorted_list) - 1))

Pretty efficient, but not worth sorting for this purpose though.

answered Feb 25, 2022 at 15:57

Chris's user avatar

ChrisChris

5,5044 gold badges44 silver badges54 bronze badges

For begginers:

def AllDifferent(s):
    for i in range(len(s)):
        for i2 in range(len(s)):
            if i != i2:
                if s[i] == s[i2]:
                    return False
    return True

Nikolay Fominyh's user avatar

answered Nov 4, 2015 at 14:37

DonChriss's user avatar

1

В этой статье мы рассмотрим 3 способа получения уникальных значений из списка в Python. Имея дело с огромным количеством необработанных данных, мы часто сталкиваемся с ситуациями, когда нам нужно извлечь уникальный и неповторяющийся набор данных из необработанного набора входных данных.

Для получения уникальных значений из списка в Python можно использовать любой из следующих способов:

  • Метод set();
  • Использование метода list.append() вместе с циклом for;
  • Использование метода Python numpy.unique().

Содержание

  1. Set() для получения уникальных значений из списка
  2. list.append() и цикл for
  3. numpy.unique() для создания списка с уникальными элементами

Set() для получения уникальных значений из списка

Set хранит в себе одну копию повторяющихся значений. Это свойство можно использовать для получения уникальных значений из списка в Python.

  • Первоначально нам нужно будет преобразовать список ввода в набор с помощью функции set().

Синтаксис:

set(input_list_name)
  • Когда список преобразуется в набор, в него помещается только одна копия всех повторяющихся элементов.
  • Затем нам нужно будет преобразовать набор обратно в список, используя следующую команду:

Синтаксис:

list(set-name)
  • Наконец, распечатайте новый список. Пример:
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 

set_res = set(list_inp) 
print("The unique elements of the input list using set():n") 
list_res = (list(set_res))
 
for item in list_res: 
    print(item) 

Вывод:

The unique elements of the input list using set():

25
75
100
20
12

list.append() и цикл for

Чтобы найти уникальные элементы, мы можем применить цикл Python for вместе с функцией list.append(), чтобы добиться того же:

  • Сначала мы создаем новый (пустой) список, т.е. res_list.
  • После этого, используя цикл for, мы проверяем наличие определенного элемента в новом созданном списке (res_list). Если элемент отсутствует, он добавляется в новый список с помощью метода append().

Синтаксис:

list.append(value)

В случае, если при обходе мы сталкиваемся с элементом, который уже существует в новом списке, то есть повторяющимся элементом, в этом случае он игнорируется циклом for. Мы будем использовать оператор if, чтобы проверить, является ли этот элемент уникальным или повторяющимся.

Пример:

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 

res_list = []

for item in list_inp: 
    if item not in res_list: 
        res_list.append(item) 

print("Unique elements of the list using append():n")    
for item in res_list: 
    print(item) 
      

Вывод:

Unique elements of the list using append():

100
75
20
12
25

numpy.unique() для создания списка с уникальными элементами

Модуль NumPy имеет встроенную функцию с именем numpy.unique для извлечения уникальных элементов данных из массива numpy.

Чтобы получить уникальные элементы из списка Python, нам нужно будет преобразовать список в массив NumPy, используя следующую команду.

Синтаксис:

numpy.array(list-name)

Затем мы будем использовать метод numpy.unique() для извлечения уникальных элементов данных из массива numpy и, наконец, распечатаем получившийся список.

Синтаксис:

numpy.unique(numpy-array-name)

Пример:

import numpy as N
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 

res = N.array(list_inp) 
unique_res = N.unique(res) 
print("Unique elements of the list using numpy.unique():n")
print(unique_res)
      

Вывод:

Unique elements of the list using numpy.unique():

[12  20  25  75 100]

( 9 оценок, среднее 3 из 5 )

Помогаю в изучении Питона на примерах. Автор практических задач с детальным разбором их решений.

В этой статье мы рассмотрим три способа получения уникальных значений из списка Python.

  • Способы получения уникальных значений из списка в Python
    • Set()
    • Python list.append() и цикл for
    • Метод numpy.unique() для создания списка с уникальными элементами
  • Заключение

Уникальные значения из списка можно извлечь с помощью:

  • Метода Python set().
  • Метода list.append() вместе с циклом for.
  • Метода numpy.unique().
  • Сначала нужно преобразовать список в набор с помощью функции set().

Синтаксис

Поскольку список преобразуется в набор, в него помещается только одна копия всех элементов.

  • Затем преобразуем набор обратно в список, используя следующую команду:

Синтаксис

  • Выводим новый список.

Пример

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 
 
set_res = set(list_inp) 
print("The unique elements of the input list using set():n") 
list_res = (list(set_res))
  
for item in list_res: 
    print(item) 

Вывод

The unique elements of the input list using set():
 
25
75
100
20
12

Чтобы найти уникальные элементы, используем цикл for вместе с функцией list.append().

  • Создадим новый список res_list.
  • С помощью цикла for проверяем наличие определенного элемента в созданном списке (res_list). Если элемент отсутствует, он добавляется в новый список с помощью метода append().

Синтаксис

Если во время переборки мы сталкиваемся с элементом, который уже существует в новом списке, то он игнорируется циклом for. Используем оператор if, чтобы проверить, является ли элемент уникальным или копией.

Пример

list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 
 
res_list = []
 
for item in list_inp: 
    if item not in res_list: 
        res_list.append(item) 
 
print("Unique elements of the list using append():n")    
for item in res_list: 
    print(item) 

Вывод

Unique elements of the list using append():
 
100
75
20
12
25

Модуль Python NumPy включает в себя встроенную функцию numpy.unique, предназначенную для извлечения уникальных элементов из массива.

  • Сначала преобразуем список в массив NumPy, используя приведенную ниже команду.

Синтаксис

Далее используем метод numpy.unique() для извлечения уникальных элементов данных из массива numpy.

  • Выводим на экран полученный список.

Синтаксис

numpy.unique(numpy-array-name)

Пример

import numpy as N
list_inp = [100, 75, 100, 20, 75, 12, 75, 25] 
 
res = N.array(list_inp) 
unique_res = N.unique(res) 
print("Unique elements of the list using numpy.unique():n")
print(unique_res)

Вывод

Unique elements of the list using numpy.unique():
 
[12  20  25  75 100]

В этой статье мы рассмотрели три способа извлечения уникальных значений из списка Python.

Добавить комментарий