Предположим, есть список, который содержит повторяющиеся числа:
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. Но достаточно будет тех, которые описаны в этой статье.
If we need to keep the elements order, how about this:
used = set()
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = [x for x in mylist if x not in used and (used.add(x) or True)]
And one more solution using reduce
and without the temporary used
var.
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = reduce(lambda l, x: l.append(x) or l if x not in l else l, mylist, [])
UPDATE — Dec, 2020 — Maybe the best approach!
Starting from python 3.7, the standard dict preserves insertion order.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
So this gives us the ability to use dict.from_keys
for de-duplication!
NOTE: Credits goes to @rlat for giving us this approach in the comments!
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = list(dict.fromkeys(mylist))
In terms of speed — for me its fast enough and readable enough to become my new favorite approach!
UPDATE — March, 2019
And a 3rd solution, which is a neat one, but kind of slow since .index
is O(n).
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = [x for i, x in enumerate(mylist) if i == mylist.index(x)]
UPDATE — Oct, 2016
Another solution with reduce
, but this time without .append
which makes it more human readable and easier to understand.
mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
unique = reduce(lambda l, x: l+[x] if x not in l else l, mylist, [])
#which can also be writed as:
unique = reduce(lambda l, x: l if x in l else l+[x], mylist, [])
NOTE: Have in mind that more human-readable we get, more unperformant the script is. Except only for the dict.from_keys
approach which is python 3.7+ specific.
import timeit
setup = "mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']"
#10x to Michael for pointing out that we can get faster with set()
timeit.timeit('[x for x in mylist if x not in used and (used.add(x) or True)]', setup='used = set();'+setup)
0.2029558869980974
timeit.timeit('[x for x in mylist if x not in used and (used.append(x) or True)]', setup='used = [];'+setup)
0.28999493700030143
# 10x to rlat for suggesting this approach!
timeit.timeit('list(dict.fromkeys(mylist))', setup=setup)
0.31227896199925453
timeit.timeit('reduce(lambda l, x: l.append(x) or l if x not in l else l, mylist, [])', setup='from functools import reduce;'+setup)
0.7149233570016804
timeit.timeit('reduce(lambda l, x: l+[x] if x not in l else l, mylist, [])', setup='from functools import reduce;'+setup)
0.7379565160008497
timeit.timeit('reduce(lambda l, x: l if x in l else l+[x], mylist, [])', setup='from functools import reduce;'+setup)
0.7400134069976048
timeit.timeit('[x for i, x in enumerate(mylist) if i == mylist.index(x)]', setup=setup)
0.9154880290006986
ANSWERING COMMENTS
Because @monica asked a good question about «how is this working?». For everyone having problems figuring it out. I will try to give a more deep explanation about how this works and what sorcery is happening here
So she first asked:
I try to understand why
unique = [used.append(x) for x in mylist if x not in used]
is not working.
Well it’s actually working
>>> used = []
>>> mylist = [u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
>>> unique = [used.append(x) for x in mylist if x not in used]
>>> print used
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']
>>> print unique
[None, None, None, None, None]
The problem is that we are just not getting the desired results inside the unique
variable, but only inside the used
variable. This is because during the list comprehension .append
modifies the used
variable and returns None
.
So in order to get the results into the unique
variable, and still use the same logic with .append(x) if x not in used
, we need to move this .append
call on the right side of the list comprehension and just return x
on the left side.
But if we are too naive and just go with:
>>> unique = [x for x in mylist if x not in used and used.append(x)]
>>> print unique
[]
We will get nothing in return.
Again, this is because the .append
method returns None
, and it this gives on our logical expression the following look:
x not in used and None
This will basically always:
- evaluates to
False
whenx
is inused
, - evaluates to
None
whenx
is not inused
.
And in both cases (False
/None
), this will be treated as falsy
value and we will get an empty list as a result.
But why this evaluates to None
when x
is not in used
? Someone may ask.
Well it’s because this is how Python’s short-circuit operators works.
The expression
x and y
first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is
returned.
So when x
is not in used (i.e. when its True
) the next part or the expression will be evaluated (used.append(x)
) and its value (None
) will be returned.
But that’s what we want in order to get the unique elements from a list with duplicates, we want to .append
them into a new list only when we they came across for a fist time.
So we really want to evaluate used.append(x)
only when x
is not in used
, maybe if there is a way to turn this None
value into a truthy
one we will be fine, right?
Well, yes and here is where the 2nd type of short-circuit
operators come to play.
The expression
x or y
first evaluates x; if x is true, its value is
returned; otherwise, y is evaluated and the resulting value is
returned.
We know that .append(x)
will always be falsy
, so if we just add one or
next to him, we will always get the next part. That’s why we write:
x not in used and (used.append(x) or True)
so we can evaluate used.append(x)
and get True
as a result, only when the first part of the expression (x not in used)
is True
.
Similar fashion can be seen in the 2nd approach with the reduce
method.
(l.append(x) or l) if x not in l else l
#similar as the above, but maybe more readable
#we return l unchanged when x is in l
#we append x to l and return l when x is not in l
l if x in l else (l.append(x) or l)
where we:
- Append
x
tol
and return thatl
whenx
is not inl
. Thanks to theor
statement.append
is evaluated andl
is returned after that. - Return
l
untouched whenx
is inl
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?
asked Mar 11, 2011 at 20:44
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
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
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
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
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 OledzkiGrzegorz Oledzki
23.5k16 gold badges67 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 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
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
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.
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ömerNico Schlömer
52.5k26 gold badges196 silver badges243 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
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
10.4k17 gold badges73 silver badges145 bronze badges
answered Sep 12, 2019 at 12:37
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
yilmazhuseyinyilmazhuseyin
6,3924 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
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
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
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
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
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
answered Nov 4, 2015 at 14:37
1
В этой статье мы рассмотрим три способа получения уникальных значений из списка 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.
В этой статье мы рассмотрим 3 способа получения уникальных значений из списка в Python. Имея дело с огромным количеством необработанных данных, мы часто сталкиваемся с ситуациями, когда нам нужно извлечь уникальный и неповторяющийся набор данных из необработанного набора входных данных.
Для получения уникальных значений из списка в Python можно использовать любой из следующих способов:
- Метод set();
- Использование метода list.append() вместе с циклом for;
- Использование метода Python numpy.unique().
Содержание
- Set() для получения уникальных значений из списка
- list.append() и цикл for
- 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 )
Помогаю в изучении Питона на примерах. Автор практических задач с детальным разбором их решений.