Checking if all elements in a list are unique
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.
Check all elements are different in the list in python
In your case you have written len(set(list)) != 1
which only works if all elements in list are same if you have two elements repeats for thousand of time then it will return length of set as two because it will have two unique elements.
So one way is that you check length of unique elements with original list if its same then function evaluates True otherwise False
def all_distinct(lis):
return len(set(lis)) == len(lis)
set(lis)
- creates set of element where all elements are unique (never repeated)len()
- returns length of set or list or string passed as argument.
In [8]: all_distinct(['a', 'a'])
Out[8]: False
In [9]: all_distinct(['a', 'a', 'x'])
Out[9]: False
In [11]: all_distinct(['a', 'b', 'x'])
Out[11]: True
You can also approach in different way as below (keeping record of occurances)
def get_occurrence(lis):
td = {}
for i in lis:
td[i] = td.setdefault(i, 0) + 1
return td
def all_distinct(lis):
dict_ = get_occurrence(lis) # this will return dict containing key as element and value of it's occurrence
return all(i==1 for i in dict_.values())
How to check if all elements of a list match a condition?
The best answer here is to use all()
, which is the builtin for this situation. We combine this with a generator expression to produce the result you want cleanly and efficiently. For example:
>>> items = [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
True
>>> items = [[1, 2, 0], [1, 2, 1], [1, 2, 0]]
>>> all(flag == 0 for (_, _, flag) in items)
False
Note that all(flag == 0 for (_, _, flag) in items)
is directly equivalent to all(item[2] == 0 for item in items)
, it's just a little nicer to read in this case.
And, for the filter example, a list comprehension (of course, you could use a generator expression where appropriate):
>>> [x for x in items if x[2] == 0]
[[1, 2, 0], [1, 2, 0]]
If you want to check at least one element is 0, the better option is to use any()
which is more readable:
>>> any(flag == 0 for (_, _, flag) in items)
True
Test if all values in a list are unique
bool isUnique = theList.Distinct().Count() == theList.Count();
Haskell - Checking if all list elements are unique
An alternative exploiting notElem
:
allDifferent :: (Eq a) => [a] -> Bool
allDifferent list = case list of
[] -> True
(x:xs) -> x `notElem` xs && allDifferent xs
Minor variant, using pattern matching directly in the equations:
allDifferent :: (Eq a) => [a] -> Bool
allDifferent [] = True
allDifferent (x:xs) = x `notElem` xs && allDifferent xs
I tend to stay away from partial functions like head,tail
, so the variants based on guards look worse to me.
Related Topics
When Should I Subclass Enummeta Instead of Enum
Python Filter List of Dictionaries Based on Key Value
Converting an Rgb Color Tuple to a Hexidecimal String
Re.Findall Not Returning Full Match
Python Script Returns Unintended "None" After Execution of a Function
How to Access Function Variables in Another Function
What Does "Bound Method" Error Mean When I Call a Function
Check If String Has Date, Any Format
How to Qcut with Non Unique Bin Edges
How to Convert an Array of Strings to an Array of Floats in Numpy
Functions That Help to Understand JSON(Dict) Structure
Attaching a Decorator to All Functions Within a Class
Boto3 to Download All Files from a S3 Bucket
Reading E-Mails from Outlook with Python Through Mapi
How to Get 2.X-Like Sorting Behaviour in Python 3.X
Python String.Strip Stripping Too Many Characters
Typeerror: Module._Init_() Takes at Most 2 Arguments (3 Given)