Check if all elements in a list are identical
Use itertools.groupby
(see the itertools
recipes):
from itertools import groupby
def all_equal(iterable):
g = groupby(iterable)
return next(g, True) and not next(g, False)
or without groupby
:
def all_equal(iterator):
iterator = iter(iterator)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == x for x in iterator)
There are a number of alternative one-liners you might consider:
Converting the input to a set and checking that it only has one or zero (in case the input is empty) items
def all_equal2(iterator):
return len(set(iterator)) <= 1Comparing against the input list without the first item
def all_equal3(lst):
return lst[:-1] == lst[1:]Counting how many times the first item appears in the list
def all_equal_ivo(lst):
return not lst or lst.count(lst[0]) == len(lst)Comparing against a list of the first element repeated
def all_equal_6502(lst):
return not lst or [lst[0]]*len(lst) == lst
But they have some downsides, namely:
all_equal
andall_equal2
can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.all_equal
andall_equal3
stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer isFalse
just by looking at the first two elements.- In
all_equal2
the content must be hashable. A list of lists will raise aTypeError
for example. all_equal2
(in the worst case) andall_equal_6502
create a copy of the list, meaning you need to use double the memory.
On Python 3.9, using perfplot
, we get these timings (lower Runtime [s]
is better):
How do I check if all elements in a list are the same?
You can use set like this
len(set(mylist)) == 1
Explanation
sets store only unique items in them. So, we try and convert the list to a set. After the conversion, if the set has more than one element in it, it means that not all the elements of the list are the same.
Note: If the list has unhashable items (like lists, custom classes etc), the set
method cannot be used. But we can use the first method suggested by @falsetru,
all(x == mylist[0] for x in mylist)
Advantages:
It even works with unhashable types
It doesn't create another temporary object in memory.
It short circuits after the first failure. If the first and the second elements don't match, it returns
False
immediately, whereas in theset
approach all the elements have to be compared. So, if the list is huge, you should prefer theall
approach.It works even when the list is actually empty. If there are no elements in the iterable,
all
will returnTrue
. But the empty list will create an emptyset
for which the length will be 0.
Python: determine if all items of a list are the same item
def all_same(items):
return all(x == items[0] for x in items)
Example:
>>> def all_same(items):
... return all(x == items[0] for x in items)
...
>>> property_list = ["one", "one", "one"]
>>> all_same(property_list)
True
>>> property_list = ["one", "one", "two"]
>>> all_same(property_list)
False
>>> all_same([])
True
Checking if each values in list are identical to another list one by one. (Python 3)
We can use a for loop to achieve this. (I know that this method is old school and you can achieve the same using one-liners by using map() and all() function )
I am writing the full code first. Then I will explain each steps.
(I am assuming that the lists will have equal number of elements.)
Code:-
list_1 = [12, 3, 45, 2, 50]
list_2 = [12, 3, 45, 2, 50]
length = len(list_1) # STEP 1
for i in range(0, length): # STEP 2
if list_1[i] != list_2[i]:
print(False)
else:
print(True)
Step 1
Identify the length of the list. This can be done by len()
function. len(list_1)
will return the length of list_1
Step 2
Iterate through each element in the first list and compare it with the corresponding element in the second list. If they are different then print False
or else print True
for i in range(0, length):
if list_1[i] != list_2[i]:
print(False)
else:
print(True)
Check if all values of array are equal
const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] ) // true
Or one-liner:
[1,1,1,1].every( (val, i, arr) => val === arr[0] ) // true
Array.prototype.every (from MDN) :
The every()
method tests whether all elements in the array pass the test implemented by the provided function.
Use all() function to check if all elements in list are in dictionary
This is very straightforward in Python. Generator expressions allow you to filter items using if
:
all(item in dictionary for item in alist if item.startswith("word"))
How do I check if all elements in a list are equal?
Some remarks:
- Indent your code for readability
- Check the case where the list only has one element
- You call your function recursively when first and second elements are distinct, but in that case you don't need it since the property is already known to be false.
Your attempt is almost good you only put the recursive call in a wrong place. Equality is transitive so you only need to compare each element with its successor and see if the property holds for the sublist. I would personally write it as follow :
(defun all-equal-p (list)
(or (null (rest list)) ;; singleton/empty
(and (equalp (first list)
(second list))
(all-equal-p (rest list)))))
Is there a better way to check if all elements in a list are named?
I am not sure if the following base R code works for your general cases, but it seems work for the ones in your post.
Define a function f
to check the names
f <- function(lst) length(lst) == sum(names(lst) != "",na.rm = TRUE)
and you will see
> f(x)
[1] TRUE
> f(y)
[1] FALSE
> f(z)
[1] FALSE
Related Topics
Convert Timestamps With Offset to Datetime Obj Using Strptime
Executing Command Using "Su -L" in Ssh Using Python
Why Does Python "Preemptively" Hang When Trying to Calculate a Very Large Number
Making Python Script Accessible System Wide
Error: Command 'Gcc' Failed with Exit Status 1 on Centos
Creating a Cron Job - Linux/Python
Python Requests Json Returns Single Quote
How to Modify Lines in a File In-Place
Gunicorn Command Not Found, But It's in My Requirements.Txt
How to Install Python on Alpine Linux
How to List All Python Virtual Environments in Linux
How to See Pip Package Sizes Installed