Check If All Elements in a List Are Identical

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:

  1. 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)) <= 1
  2. Comparing against the input list without the first item

    def all_equal3(lst):
    return lst[:-1] == lst[1:]
  3. 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)
  4. 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:

  1. all_equal and all_equal2 can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.
  2. all_equal and all_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 is False just by looking at the first two elements.
  3. In all_equal2 the content must be hashable. A list of lists will raise a TypeError for example.
  4. all_equal2 (in the worst case) and all_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):

for a list with a difference in the first two elements, groupby is fastestfor a list with no differences, count(l[0]) is fastest

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:

  1. It even works with unhashable types

  2. It doesn't create another temporary object in memory.

  3. It short circuits after the first failure. If the first and the second elements don't match, it returns False immediately, whereas in the set approach all the elements have to be compared. So, if the list is huge, you should prefer the all approach.

  4. It works even when the list is actually empty. If there are no elements in the iterable, all will return True. But the empty list will create an empty set 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



Leave a reply



Submit