Check If All Items Are the Same in a List

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

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 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

Check if all items are the same in a List

Like this:

if (list.Distinct().Skip(1).Any())

Or

if (list.Any(o => o != list[0]))

(which is probably faster)

Check if all elements of a list are of the same type

Try using all in conjunction with isinstance:

all(isinstance(x, int) for x in lst)

You can even check for multiple types with isinstance if that is desireable:

all(isinstance(x, (int, long)) for x in lst)

Not that this will pick up inherited classes as well. e.g.:

class MyInt(int):
pass

print(isinstance(MyInt('3'),int)) #True

If you need to restrict yourself to just integers, you could use all(type(x) is int for x in lst). But that is a VERY rare scenario.


A fun function you could write with this is one which would return the type of the first element in a sequence if all the other elements are the same type:

def homogeneous_type(seq):
iseq = iter(seq)
first_type = type(next(iseq))
return first_type if all( (type(x) is first_type) for x in iseq ) else False

This will work for any arbitrary iterable, but it will consume "iterators" in the process.

Another fun function in the same vein which returns the set of common bases:

import inspect
def common_bases(seq):
iseq = iter(seq)
bases = set(inspect.getmro(type(next(iseq))))
for item in iseq:
bases = bases.intersection(inspect.getmro(type(item)))
if not bases:
break
return bases

Python list: check if all items are the same or not

This compares every element of the list to the first one:

listOfStrings = ['ep:1000' , 'ep:4444', 'ep:1000', 'ep:1000', 'ep:1000', 'ep:1000']
check = all(x == listOfStrings[0] for x in listOfStrings)

And returns false for your test case.

How to check if a list contains all the elements of another list INCLUDING duplicates

Repeated calls to list.count (for the same list) are very inefficient. You can use collections.Counter and how it implements differences:

from collections import Counter

def contains(l1, l2):
return not (Counter(l2) - Counter(l1))

>>> contains(["A", "A", "A", "b", "b"], ["A", "A", "b", "b"])
True
>>> contains(["a", "a", "b"], ["a", "b"])
True
>>> contains(["a", "b"], ["a", "a", "b"])
False
>>> contains(["a", "a", "b"], ["a", "b", "c"])
False

Better way to check if all lists in a list are the same length?

I'd do it with a generator expression and all:

it = iter(lists)
the_len = len(next(it))
if not all(len(l) == the_len for l in it):
raise ValueError('not all lists have same length!')

This avoids checking the length of the first list twice and does not build throwaway list/set datastructures.

all also evaluates lazily, which means it will stop and return False as soon as the first list which differs in length is yielded by the generator.

Check if all values in list are greater than a certain number

Use the all() function with a generator expression:

>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False

Note that this tests for greater than or equal to 30, otherwise my_list1 would not pass the test either.

If you wanted to do this in a function, you'd use:

def all_30_or_up(ls):
for i in ls:
if i < 30:
return False
return True

e.g. as soon as you find a value that proves that there is a value below 30, you return False, and return True if you found no evidence to the contrary.

Similarly, you can use the any() function to test if at least 1 value matches the condition.



Related Topics



Leave a reply



Submit